kapso
kapso

Reputation: 11903

Extracting array from Ruby Hash

I have the following Hash -

{ result: [ {id: 378, name: 'Pete'}, {id: 567, name: 'Pete'} ] }

I want to extract array of id's from this hash, something like this -

[378, 567]

Whats the shortest way to do it, apart from looping through the result array. Theres a map method for this but I am not quite sure how to use it.

Help is appreciated.

Upvotes: 0

Views: 1475

Answers (2)

Reza
Reza

Reputation: 3038

I didn't use map in order to get those values. You can use the following technique:

    a = { result: [ {id: 378, name: 'Pete'}, {id: 567, name: 'Pete'} ] }
    i= [0,1]
    output_value  = []
    for b in i 
            output_value  << a.values[0][b][:id]
    end 

    output_value 

Upvotes: 0

rjz
rjz

Reputation: 16510

That map method is pretty convenient. If your input looks like this:

input = { :result => [ {:id => 378, :name => 'Pete'}, {:id => 567, :name => 'Pete'} ] }

You can extract the ids like so:

ids = input[:result].map{ |obj| obj[:id] }

puts ids.inspect

Check it out.

Upvotes: 3

Related Questions