简体   繁体   中英

Selecting items from a Ruby Hash

I have a hash in Ruby that looks like this:

{"NameValues"=>[
    {"Name"=>"Field 1", "Values"=>["Data 1"]}, 
    {"Name"=>"Field 2", "Values"=>["Data 2"]}, 
    {"Name"=>"Field 3", "Values"=>["Data 3"]}, 
    {"Name"=>"Field 4", "Values"=>["Data 4"]}, 
    {"Name"=>"Field 5", "Values"=>["Data 5"]}
]}

I want to select the contents of the "Values" element by using the name from the "Names" element, eg, locate the "Data 3" string by searching for "Field 3" etc.

You could use the Enumerable#find method to find the hash by name:

hash = {"NameValues"=>[
    {"Name"=>"Field 1", "Values"=>["Data 1"]}, 
    {"Name"=>"Field 2", "Values"=>["Data 2"]}, 
    {"Name"=>"Field 3", "Values"=>["Data 3"]}, 
    {"Name"=>"Field 4", "Values"=>["Data 4"]}, 
    {"Name"=>"Field 5", "Values"=>["Data 5"]}
]}

p hash['NameValues'].find{ |h| h['Name'] == 'Field 3'}['Values']
#=> ["Data 3"]

find basically iterates through the NameValues array until a matching element is found. You can then get the Values from the returned element.

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