如何从数组中的哈希中获取所有值?

时间:2015-08-31 16:37:02

标签: arrays ruby hash

我有以下哈希wbs_items

wbs_items = {"Architecture"=>"architecture", "Auditing"=>"auditing", "Consulting"=>"consulting", "Delivery"=>"delivery", "Development"=>"development", "Engineering"=>"engineering", "Environment / IT"=>"environment", "Graphic Design"=>"graphic_design", "Management"=>"management", "Requirements"=>"requirements", "Research"=>"research", "Support"=>"support", "System Design"=>"system_design", "Test & Eval"=>"test_and_evaluation", "Writing"=>"writing"}

以下数组disciplines

disciplines = ["architecture", "auditing", "consulting", "development", "engineering", "environment", "graphic_design", "management", "system_design", "test_and_evaluation", "writing"]

我想只从散列中获取具有数组值的键和值。我该怎么做?

3 个答案:

答案 0 :(得分:1)

试试这个:

wbs_items.values & disciplines

答案 1 :(得分:1)

怎么样:

wbs_items.select { |k,v| disciplines.include?(v) }

答案 2 :(得分:0)

inverted = wbs_items.invert
disciplines.to_enum.with_object({}){|k, h| h[inverted[k]] = k}