开发者

How do I... truncate string in an array

开发者 https://www.devze.com 2022-12-25 21:40 出处:网络
In a ruby on rails app, I build an array of Project Names and project id values, but want to truncate the length of the names.Current code is:

In a ruby on rails app, I build an array of Project Names and project id values, but want to truncate the length of the names. Current code is:

names  = active_projects.collect {|proj| [proj.name, proj.id]}

I have tried to add a truncate function to the block, but am getting undefined method for class error.

Thanks in advance - I just 开发者_如何学Pythoncannot wrap my head around this yet.


Assuming I understood the question properly:

max_length = 10 # this is the length after which we will truncate
names = active_projects.map { |project|
  name = project.name.to_s[0..max_length] # I am calling #to_s because the question didn't specify if project.name is a String or not
  name << "…" if project.name.to_s.length > max_length # add an ellipsis if we truncated the name
  id = project.id
  [name, id]
}


Try Following

name=[]
active_projects.collect {|proj| name << [proj.name, proj.id]}

EDITED this should be

names= active_projects.collect {|proj|  [proj.name.to_s[0..10], proj.id]}


In a Rails application you can use the truncate method for this.

If your code isn't in a view then you will need to include the TextHelper module in order to make the method available:

include ActionView::Helpers::TextHelper

you can then do:

names = active_projects.collect { |proj| [truncate(proj.name), proj.id] }

The default behaviour is to truncate to 30 characters and replace the removed characters with '...' but this can be overridden as follows:

names = active_projects.collect {
  # truncate to 10 characters and don't use '...' suffix
  |proj| [truncate(proj.name, :length => 10, :omission => ''), proj.id]
}
0

精彩评论

暂无评论...
验证码 换一张
取 消