Ruby On Rails:在循环中连接字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14521221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby On Rails: Concatenate String in loop
提问by neeraj
I am new to RoR. I was trying to find a way over googling to concatenate the string in a loop in Controller.
我是 RoR 的新手。我试图通过谷歌搜索找到一种方法来在 Controller 的循环中连接字符串。
assets = Asset.where({ :current_status => ["active"] }).all
assets.each do |a|
string = string + ":"+ a.movie_title
end
I want to concatenate attribute "movie_title" as a string that would be colon separated.
我想将属性“movie_title”连接为一个以冒号分隔的字符串。
but i get error
但我得到错误
undefined method `+' for nil:NilClass
回答by Jakob S
The easiest way is probably:
最简单的方法大概是:
string = assets.collect(&:movie_title).join(':')
collect(&:movie_title)is the same as collect { |asset| asset.movie_title }, which returns an Array of the movie titles. join(':')creates a String with the values from the Array separated by :.
collect(&:movie_title)与 相同collect { |asset| asset.movie_title },它返回电影片名的数组。join(':')使用 Array 中的值创建一个字符串,由:.
回答by Raghuveer
Try this
尝试这个
assets = Asset.where({ :current_status => ["active"] }).all
string = ""
if assets.present?
assets.each do |a|
string = string + ":"+ a.movie_title
end
end
回答by Matteo
Why not just this:
为什么不只是这个:
"#{string} : #{a.movie_title}"
If they are nil you will get " : "
如果它们为零,您将得到 " : "

