Aron Solberg
Aron Solberg

Reputation: 6858

Whats the ruby way to extract an array of values from an array of hashes?

Suppose I have an array like this:

starting_array = [{key1: 'someKey1Value', key2: 'someKey2Value'}, {key1: 'anotherKey1Value', key2: 'anotherKey2Value'}]

I want to end up with this:

desired_array = ['someKey2Value', 'anotherKey2Value']

Whats the best way to extract all the values for key2 into a separate array?

Upvotes: 0

Views: 32

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Use Array#map :-

starting_array.map { |hash| hash[:key2] }

Upvotes: 2

Related Questions