Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: new array from one value in an array of objects

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!

like image 597
Andrew Avatar asked Mar 04 '11 15:03

Andrew


People also ask

How do you add an array to another array in Ruby?

Ruby | Array concat() operation Array#concat() : concat() is a Array class method which returns the array after appending the two arrays together.

How do you split an array in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

How do you filter an array of objects in Ruby?

You can use the select method in Ruby to filter an array of objects. For example, you can find all the even numbers in a list.


2 Answers

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] }
like image 198
htanata Avatar answered Oct 02 '22 15:10

htanata


How about:

a.collect {|f| f.name}
like image 35
grifaton Avatar answered Oct 02 '22 15:10

grifaton