Ruby比较和匹配数组到数组的哈希值

时间:2014-11-15 11:47:41

标签: ruby arrays

我已经定义了一个数组的静态哈希,其主要设施列表按类别组织:

amenities = {
    "food" => [
        "Bar/lounge",
        "Restaurant",
        "Room service"
    ],
    "transportation" => [
        "Shuttle",
        "Ski shuttle",
        "Airport transportation"

    ],
    "facilities" => [
        "Fitness facilities",
        "Indoor pool",
        "Business center",
    ]
}

我正在使用API​​返回一个扁平的,未分类的数组中的设施列表,如下所示:

response = [
    "Bar/lounge",
    "Shuttle",
    "Ski shuttle",
    "Indoor pool"
]

是否有一种直接的方法来迭代并将响应列表与主列表进行比较/匹配,以找出响应属性所属的类别?通过上面的例子,理想的结果是:

result = {
    "food" => [
        "Bar/lounge"
    ],
    "transportation" => [
        "Shuttle",
        "Ski shuttle"

    ],
    "facilities" => [
        "Indoor pool"
    ]
}

因此,只有响应列表才会在结果哈希中进行组织,并按照主列表中的定义按类别进行组织。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:3)

我会这样做:

amenities.merge(amenities) { |*_,a| a & response }
  #=> {"food"=>["Bar/lounge"],
  #    "transportation"=>["Shuttle", "Ski shuttle"],
  #    "facilities"=>["Indoor pool"]}

答案 1 :(得分:1)

一种方法可能是:

result = {}
amenities.each do |key, values|
  result[key] = values.select{|v| response.include?(v) }
end
p result
#=> {
      "food"=>["Bar/lounge"], 
      "transportation"=>["Shuttle", "Ski shuttle"], 
      "facilities"=>["Indoor pool"]
    }

或:

p amenities.each_with_object({}) { |(key, values), result| 
  result[key] = values.select{|v| response.include?(v) } 
}
#=> {
      "food"=>["Bar/lounge"], 
      "transportation"=>["Shuttle", "Ski shuttle"], 
      "facilities"=>["Indoor pool"]
    }

或:

p amenities.inject({}) { |result, (key, values)|
     result[key] = values.select{|v| response.include?(v) }; result
   }
#=> {
      "food"=>["Bar/lounge"], 
      "transportation"=>["Shuttle", "Ski shuttle"], 
      "facilities"=>["Indoor pool"]
    }

答案 2 :(得分:1)

amenities = {
  "food" => [
    "Bar/lounge",
    "Restaurant",
    "Room service"
  ],
  "transportation" => [
    "Shuttle",
    "Ski shuttle",
    "Airport transportation"

  ],
  "facilities" => [
    "Fitness facilities",
    "Indoor pool",
    "Business center",
  ]
}

response = [
  "Bar/lounge",
  "Shuttle",
  "Ski shuttle",
  "Indoor pool"
]

result = response.each_with_object({}) do |item, hash|
  search = amenities.find { |_,values| values.include?(item) }
  (hash[search.first] ||= []) << item unless search.nil?
end

puts result
# => {"food"=>["Bar/lounge"],
#     "transportation"=>["Shuttle", "Ski shuttle"],
#     "facilities"=>["Indoor pool"]}