您可以通过以下方式将 ID 值读入数组进行处理:
require 'yaml'
yml = <<-_end_
---
Level1:
Seattle:
Name: "Rick"
ID: "95155"
Time: "2:00 PM"
Car: "Hyundai"
Denver:
Name: "Arnold"
ID: "82594"
Time: "2:00 PM"
Car: "Mitsubishi"
Level 2:
San Antonio:
Name: "James"
ID: "96231"
Time: "2:00 PM"
Car: "Honda"
Minneapolis:
Name: "Ron"
ID: "73122"
Time: "2:00 PM"
Car: "Dodge"
_end_
hsh = YAML.load(yml)
# => {"Level1"=>
# {"Seattle"=>
# {"Name"=>"Rick", "ID"=>"95155", "Time"=>"2:00 PM", "Car"=>"Hyundai"},
# "Denver"=>
# {"Name"=>"Arnold",
# "ID"=>"82594",
# "Time"=>"2:00 PM",
# "Car"=>"Mitsubishi"}},
# "Level 2"=>
# {"San Antonio"=>
# {"Name"=>"James", "ID"=>"96231", "Time"=>"2:00 PM", "Car"=>"Honda"},
# "Minneapolis"=>
# {"Name"=>"Ron", "ID"=>"73122", "Time"=>"2:00 PM", "Car"=>"Dodge"}}}
def hash_value(hsh)
keys = hsh.keys
keys.each_with_object([]){|e,ar| hsh[e].is_a?(Hash) ? ar << hash_value(hsh[e]).flatten.uniq : ar << hsh["ID"]}.flatten
end
hash_value(hsh) # => ["95155", "82594", "96231", "73122"]