在 ruby on rails 应用程序中,我构建了一个项目名称和项目 id 值的数组,但想要截断名称的长度。当前代码是:
names = active_projects.collect {|proj| [proj.name, proj.id]}
我试图向块中添加一个截断函数,但我得到了类错误的未定义方法。
在此先感谢-我还不能解决这个问题。
尝试关注
name=[]
active_projects.collect {|proj| name << [proj.name, proj.id]}
编辑这应该是
names= active_projects.collect {|proj| [proj.name.to_s[0..10], proj.id]}
假设我正确理解了这个问题:
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]
}
在 Rails 应用程序中,您可以为此使用truncate方法。
如果您的代码不在视图中,那么您需要包含 TextHelper 模块才能使该方法可用:
include ActionView::Helpers::TextHelper
然后你可以这样做:
names = active_projects.collect { |proj| [truncate(proj.name), proj.id] }
默认行为是截断为 30 个字符并将删除的字符替换为 '...' 但这可以被覆盖,如下所示:
names = active_projects.collect {
# truncate to 10 characters and don't use '...' suffix
|proj| [truncate(proj.name, :length => 10, :omission => ''), proj.id]
}