eudaimonia
eudaimonia

Reputation: 1536

Get id from hash in array of hashes

I have an array of hashes:

g_list = [
  {:groups => [{:id => 5}]},
  {:groups => [{:id => 6}]}
]

I need to get an array of :id values from the structure. I want to get [5, 6].

How can I iterate through an array of hashes, and dig the items inside?

I tried to use map and dig:

g_list.map{|g| g.dig(:groups, :id)}

but I receive an error TypeError: no implicit conversion of Symbol into Integer. I also tried to handle it with each loop for single example of groups:

g_list.each do |g|
   groups = g.dig(:groups)
   puts groups[:id]
end

but I still get the same error. I finally wrote this:

arr = g_list.map {|g| g.dig(:groups).map{|i| i[:id]}}.flatten

and it returns what I expected, but I wonder whether I can write this in a better way.

Upvotes: 1

Views: 1449

Answers (2)

3limin4t0r
3limin4t0r

Reputation: 21110

The following returns a list with all group ids, even if an element contains more than one group.

g_list = [
  {:groups => [{:id => 5}]},
  {:groups => [{:id => 6}]}
]

arr = g_list.flat_map { |g| g[:groups] }.map { |i| i[:id] }
arr #=> [5, 6]

g_list = [
  {:groups => [{:id => 5}]},
  {:groups => [{:id => 6}, {:id => 7}]}
]

arr = g_list.flat_map { |g| g[:groups] }.map { |i| i[:id] }
arr #=> [5, 6, 7]

Assuming all elements have a :groups key.

Upvotes: 0

sawa
sawa

Reputation: 168081

Array indices can be passed as part of the arguments to your dig call. You want index 0 to extract the single element from the array.

g_list.map{|g| g.dig(:groups, 0, :id)}
# => [5, 6]

Upvotes: 3

Related Questions