Ruby On Rails:循环中的Concatenate String

nee*_*raj 7 loops ruby-on-rails string-concatenation

我是RoR的新手.我试图在googling中找到一种方法来连接Controller中循环中的字符串.

assets = Asset.where({ :current_status => ["active"] }).all
assets.each do |a|
      string = string + ":"+ a.movie_title 
end
Run Code Online (Sandbox Code Playgroud)

我想将属性"movie_title"连接为一个冒号分隔的字符串.

但我得到错误

undefined method `+' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

Jak*_*b S 17

最简单的方法可能是:

string = assets.collect(&:movie_title).join(':')
Run Code Online (Sandbox Code Playgroud)

collect(&:movie_title)collect { |asset| asset.movie_title }返回电影标题数组的相同.join(':')使用Array中的值分隔创建一个String :.


Rag*_*eer 9

试试这个

assets = Asset.where({ :current_status => ["active"] }).all
string = ""
if assets.present?
 assets.each do |a|
  string = string + ":"+ a.movie_title 
 end
end
Run Code Online (Sandbox Code Playgroud)


Mat*_*teo 9

为什么不这样:

"#{string} : #{a.movie_title}"
Run Code Online (Sandbox Code Playgroud)

如果他们没有,你就会得到 " : "