简体   繁体   中英

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

I have a array of hashes-

[{"id"=>1,
  "name"=>"Bose Headphones",
  "created_at"=>"2015-11-25T10:40:29.120Z",
  "updated_at"=>"2015-11-25T10:40:29.120Z",
  "description"=>"Bose",
  "active"=>true},
 {"id"=>3,
  "name"=>"test topic",
  "created_at"=>"2015-11-30T14:34:03.087Z",
  "updated_at"=>"2015-11-30T14:34:03.087Z",
  "description"=>"test",
  "active"=>true},
 {"id"=>4,
  "name"=>"Wireless Mouse",
  "created_at"=>"2015-11-30T14:35:16.583Z",
  "updated_at"=>"2015-11-30T14:35:16.583Z",
  "description"=>"WM",
  "active"=>true},
 {"id"=>5,
  "name"=>"Fit Band",
  "created_at"=>"2015-12-01T04:39:03.034Z",
  "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 .sample 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)

我已经对此进行了测试,它似乎按预期工作!

arrOfHashes.map{|i| i["name"]}.sample(1)

您可以跳过map并从随机哈希中获取"name"

arrOfHash.sample['name']

There is gem called vine in ruby which lets you access the values based on key. I would do something like (assuming the above array's name is array_of_hashes)

require 'vine'
name_list = []
array_of_hashes.each do |hash|
   name_list << hash.access("name")
end
puts "All the extracted names from array #{name_list}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM