MrB
MrB

Reputation: 2225

Getting a list of names from a list of objects

I have an array "Groups". Each of the group-objects has an attribute name. I want to get a list of all those names, and maybe also the corresponding IDs, to put in a drop-down select in rails.

Is there a very ruby way to do this?

In PHP, I'd do something like:

group_names = Array.new
Groups.each do |group|
  group_names << group.name
end

But this doesn't feel very rubyish at all.

Upvotes: 0

Views: 494

Answers (2)

steenslag
steenslag

Reputation: 80065

Use map

group_names = groups.map{|group| group.name}

or the short form

group_names = groups.map(&:name)

Upvotes: 3

Syed Aslam
Syed Aslam

Reputation: 8807

I think what you're looking for is essentially this:

select(object, method, choices, options = {}, html_options = {})

For example:

<%= f.select("type_id", Object.all.collect {|o| [ o.name, o.id ] }) %>

Checkout more options here.

Upvotes: 1

Related Questions