0

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.

2 Answers 2

3

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.

1
  • For some collect method feels more intuitive.. ; )
    – ok32
    May 10, 2012 at 23:34
0

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 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.