Rahul Vig Rahul Vig - 4 years ago 93
Ruby Question

How to get all values for a key from an array of hashes?

I have a array of hashes-

[{"id"=>1, "name"=>"Bose Headphones",
"updated_at"=>"2015-11-25T10:40:29.120Z", "description"=>"Bose",
"active"=>true}, {"id"=>3, "name"=>"test topic",
"updated_at"=>"2015-11-30T14:34:03.087Z", "description"=>"test",
"active"=>true}, {"id"=>4, "name"=>"Wireless Mouse",
"updated_at"=>"2015-11-30T14:35:16.583Z", "description"=>"WM",
"active"=>true}, {"id"=>5, "name"=>"Fit Band",
"updated_at"=>"2015-12-01T04:39:03.034Z", "description"=>"Fitness
Band", "active"=>true}]

I want to get to all the name values in an array and then use
to get whatever number I want from the list.
The way I am trying is-

arr = []
arr = arrOfHash.map{|x| "#{x['name']}"}.sample(1)

This is giving me

Value cannot be an Array when 'multiple' attribute is not present. Not
a Array (ArgumentError)

Answer Source

I have tested this and it seem to work as expected!

arrOfHashes.map{|i| i["name"]}.sample(1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download