1

I have the following hash. Using ruby, I want to get the value of "runs". I can't figure out how to do it. If I do my_hash['entries'], I can dig down that far. If I take that value and dig down lower, I get this error: no implicit conversion of String into Integer:

{"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588, ...

3 Answers 3

3

Assuming that you want to lookup values by id, Array#detect comes to the rescue:

h = {"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588}]}]}
#           ⇓⇓⇓⇓⇓⇓⇓ lookup element with id = 7 
h['entries'].detect { |e| e['id'] == 7 }['runs']
            .detect { |e| e['id'] == 2588 }
#⇒ { "id" => 2588 }
Sign up to request clarification or add additional context in comments.

2 Comments

It is working fine. I didn't knew about detect, learned a new method, thanks. But I think e['id'] = 7 should be e['id'] == 7 right?
Oh, indeed, sorry for that. Updated.
2

As you have an array inside the entries so you can access it using an index like this:

my_hash["entries"][0]["runs"]

You need to follow the same for accessing values inside the runs as it is also an array.

Hope this helps.

Comments

2

I'm not sure about your hash, as it's incomplete. So , guessing you have multiple run values like:

hash = {"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588}]},
                                {"id"=>"8", "runs"=>[{"id"=>2589}]},
                                {"id"=>"9", "runs"=>[{"id"=>2590}]}]}

Then, you can do

hash["entries"].map{|entry| entry["runs"]}

OUTPUT

[[{"id"=>2588}], [{"id"=>2589}], [{"id"=>2590}]]

1 Comment

Adding up more to your answer: hash["entries"].map{|entry| entry["runs"]}.flatten.map{ |run| run["id"] } will return only the ids.

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.