6

Forgive me if this has already been asked, I couldn't find it.

I have an array of objects, like:

[<#Folder id:1, name:'Foo', display_order: 1>,
<#Folder id:1, name:'Bar', display_order: 2>,
<#Folder id:1, name:'Baz', display_order: 3>]

I'd like to convert that array into an array just of the names, like:

['Foo','Bar','Baz']

and, while I'm at it it would be nice if I could use the same technique down the road to create an array from two of the parameters, ie name and display order would look like:

[['Foo',1],['Bar',2],['Baz',3]]

What's the best 'Ruby Way' to do this kind of thing?

Thanks!

2
  • Thanks for the many answers! htanata's was the most complete. Commented Mar 4, 2011 at 16:00
  • +1 for your first step into functional programming. Commented Mar 6, 2011 at 22:25

4 Answers 4

16

How about these?

# ['Foo','Bar','Baz']
array = folders.map { |f| f.name }
# This does the same, but only works on Rails or Ruby 1.8.7 and above.
array = folders.map(&:name)

# [['Foo',1],['Bar',2],['Baz',3]]
array = folders.map { |f| [f.name, f.display_order] }
Sign up to request clarification or add additional context in comments.

1 Comment

To clarify, f.map(&:name) works without Rails in 1.8.7 and (at least) 1.9.2.
3

How about:

a.collect {|f| f.name}

1 Comment

or use a.collect! if you really want to replace it. For the second question: Hust extend it a bit to a.collect{|f| [f.name, f.display_order]}
0

You can do

array.map { |a| [a.name, a.display_order] }

Comments

0

To get ['Foo','Bar','Baz'] , you can do: array.map(&:name)

For the second one you could use array.map {|a| [a.id, a.name] }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.