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!
Ruby | Array concat() operation Array#concat() : concat() is a Array class method which returns the array after appending the two arrays together.
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.
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.
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] }
How about:
a.collect {|f| f.name}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With