Turn an array of hashes into an array

When using objects returned by an ActiveRecord proxy using a loop, if that is fine in the view, but sometimes I want to turn only one of the common hash attributes into an array. I find that I am doing this a lot, which leads to looking somewhat verbose:

 forum_roles = []

 @forum #=> [{id: 0, name: 'a'},{id: 1, name: 'b'}]

 @forum.each do |role|
    forum_roles << role.name
 end

 forum_roles #=> ['a','b']

Just wondering if there is an easier way to get to ['a','b']

+4
source share
1 answer

Use Array # map when you have an array of hashes

forum_roles = @forum.map { |role| role[:name] }
forum_roles # ['a','b']

UPDATE:

There is a shorcut with ActiveRecord objects, as @vee commented

@forum.map(&:name)

If you have an ActiveRecord relationship and you only need a column array, use pluck

@forum.pluck(:name)
+5
source

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


All Articles