Home > Mobile >  Retrieve value from Array of Hashes Ruby
Retrieve value from Array of Hashes Ruby

Time:11-04

I have an array of hashes in ruby like this

blah = [{"key1"=>"value1","key2"=>"value2","key3"=>"value3"....}]

Now let's say I want to get the value of key2.

What I am doing is puts "key 2 is #{blah["key2"]}", but then I get ERROR: "no implicit conversion of String into Integer (TypeError)"

CodePudding user response:

blah is an array so you could have more than one hash inside it with a "key2" key. let's find them all

p blah.map { |h| h['key2'] }

or if you know there is just one hash in your array

p blah[0]['key2']
  • Related