0

I have a hash and an array. I want to check whether an array element is in the hash as a key, and if not, delete the key from the hash.

RegionScoreHash={"A"=>1, "B"=>0, "C"=>0, "D"=>1, "E"=>0, "F"=>0, "G"=>0}
RegionsArray=["B", "C", "D", "E", "F"]

Result Required: Hash with elements present in array (A and G regions removed)

ResultHash={"B"=>0, "C"=>0, "D"=>1, "E"=>0, "F"=>0}

4 Answers 4

3

Use Array's delete_if method to modify the hash in place.

RegionScoreHash.delete_if { |k| !RegionsArray.include?(k) }

or use something like select if you want a new result.

result = RegionScoreHash.select { |k| RegionsArray.include?(k) }
Sign up to request clarification or add additional context in comments.

Comments

1

Deleting is inefficient.

ResultHash = RegionsArray.inject({}){|h, k| h[k] = RegionScoreHash[k]; h}

Comments

0

Try this

 RegionScoreHash={"A"=>1, "B"=>0, "C"=>0, "D"=>1, "E"=>0, "F"=>0, "G"=>0} 
 RegionsArray=["B", "C", "D", "E", "F"]
 RegionScoreHash.delete_if {|a| !RegionsArray.include?(a)}

As advice the ruby way should be region_score_hash instead RegionScoreHash.

Comments

0

Since you've tagged ruby-on-rails, let's assume you have ActiveSupport's extensions to Enumerable, which allows use of exclude?

Combine it with Hash's delete_if method

RegionScoreHash.delete_if { |k, _v| RegionsArray.exclude?(k) }

and you should get back a hash with only keys that are present in RegionsArray.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.