0

我有一个看起来像这样的 yml 文件:

Level 1:
  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

我需要将这些ID值读入一个数组进行处理,然后将它们从另一个数组中删除。有什么好的方法可以解决这个问题?

4

2 回答 2

1

您可以通过以下方式将 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"]
于 2013-08-12T18:45:21.527 回答
0

要解析 YAML,如果它包含在文件中,则:

levels = YAML.load_file(path)

如果它包含在字符串中,则:

levels = YAML.load(path)

解析后,将 ids 放入数组中:

ids = levels.values.flat_map(&:values).map do |city|
  city['ID']
end

结果:

p ids # => ["95155", "82594", "96231", "73122"]

要从另一个 id 数组中删除这些 id:

another_array_of_ids = ["123456", "82594", "96231"]
another_array_of_ids -= ids
p another_array_of_ids # => ["123456"]
于 2014-03-11T12:41:10.867 回答