user929062
user929062

Reputation: 817

How to create an array with help of a loop

I have a model Image:

class Image < ActiveRecord::Base
  attr_accessible :date, :description, :name, :quality, :size
end

I now have an instance variable with a bunch of images:

@images = Image.where("id<30")

I want to create a @keywords variable with all the names of the images. In the Rails console I can do:

for i in [email protected]
  puts @image[i].name
end

and I get a list of all the name of the images.

How can I define the @keywords variable in my images_controller in order to store this list in an array?

@keywords = ...?

The output should be a list, preferrably comma seperated, with the image names:

"Blue ocean, Green leafs, Sunset in New York"

Upvotes: 1

Views: 248

Answers (1)

Scott S
Scott S

Reputation: 2746

@keywords = @images.collect{|i| i.name}.join(",")

This will get an array of all the names and join them into a comma-separated string.

Upvotes: 4

Related Questions