Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby On Rails: Concatenate String in loop

I am new to RoR. I was trying to find a way over googling to concatenate the string in a loop in 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.

but i get error

undefined method `+' for nil:NilClass
like image 290
neeraj Avatar asked Jan 25 '13 11:01

neeraj


1 Answers

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 :.

like image 106
Jakob S Avatar answered Oct 12 '22 23:10

Jakob S