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.

Sign up to request clarification or add additional context in comments.

1 Comment

For some collect method feels more intuitive.. ; )
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 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.