从另一个项目中排除一个项目列表

时间:2013-08-12 17:37:46

标签: ruby yaml

我有一个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值读入数组进行处理,然后将其从另一个数组中删除。有什么好方法可以解决这个问题?

2 个答案:

答案 0 :(得分: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"]

答案 1 :(得分:0)

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

levels = YAML.load_file(path)

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

levels = YAML.load(path)

解析后,将ID转换为数组:

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"]