Snubber
Snubber

Reputation: 1024

How do I get all the values from a hash that are in an array?

I have the following 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"}

And the following array disciplines:

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

I want to get only the keys and values from the hash that have values from the array. How would I do that?

Upvotes: 0

Views: 55

Answers (3)

sawa
sawa

Reputation: 168071

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

Upvotes: 0

janki
janki

Reputation: 101

What about :

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

Upvotes: 1

David Grayson
David Grayson

Reputation: 87376

Try this:

wbs_items.values & disciplines

Upvotes: 1

Related Questions