2

I have these hashes:

hash  = {1 => "popcorn", 2 => "soda"}
other_hash = {1 => "dave", 2 => "linda", 3 => "bobby_third_wheel"}

I would like to replace the id reference with the name associated to the id in the second hash, if there is a record in other_hash that has nothing to match, it should just be dropped in the resulting hash. Like this:

the_one_hash_to_rule_them_all = {"dave" => "popcorn", "linda" => "soda"}

4 Answers 4

3

You can easly use this each_with_object method on "primary" hash with names.

other_hash.each_with_object({}) { |(id, name), h| h[name] = hash[id] if hash.key?(id) }
# => {"dave"=>"popcorn", "linda"=>"soda"}
Sign up to request clarification or add additional context in comments.

Comments

3
hash.each_with_object({}){|(k,v), res| res[other_hash[k]] = v}
# => {"dave"=>"popcorn", "linda"=>"soda"}

Comments

2

First, an "array-comprehension" with the pattern enumerable.map { expr if condition }.compact and finally an Array#to_h.

h = other_hash.map { |k, v| [v, hash[k]] if hash.has_key?(k) }.compact.to_h
#=> {"dave"=>"popcorn", "linda"=>"soda"}

Also:

h = other_hash.select { |k, v| hash.has_key?(k) }.map { |k, v| [v, hash[k]] }.to_h

2 Comments

That is exactly what I was looking for! thank you so much. I want to name this question better. I feel that people will want to at some stage do this. how could I improve it? I was going to use replace hash key with another hash value. but there is a replace method that will do terrible things.
Note that Array#to_h is available from Ruby 2.1.
2
hash.map{|k, v| [other_hash[k], v]}.to_h
# => {"dave"=>"popcorn", "linda"=>"soda"}

1 Comment

In lower ruby versions use Hash[hash.map{|k, v| [other_hash[k], v]}]

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.