How do I... truncate string in an array
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]
}
精彩评论