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

Forgive me if this has already been asked, I could not find it.

I have an array of objects, for example:

[<#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 would like to convert this array to an array of only names, for example:

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

and although I am in this, it would be nice if I could use the same technique in the future to create an array of two parameters, that is, the name and display order would look like this:

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

What is the best "Ruby Way" for this?

Thanks!

+4
source share
4 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] } 
+11
source

What about:

 a.collect {|f| f.name} 
+2
source

You can do

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

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

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

0
source

Source: https://habr.com/ru/post/1342307/


All Articles