1

I can't seem to figure this one out. If I have two hashes, where a value in the first hash should always match a key in the 2nd hash:

hash1 = { :table => 'name', :action => 'view' }
hash2 = { 'name'  => 'first_name', 'group'   => 'user_group' }

The key :table is a constant, but the value is dynamic. How can I swap the value in hash1 with the value in hash2, where the key matches the value in hash1? Without knowing what the actual key or value will be (other than :table in hash1)? Hope that makes sense, the updated hash1 (or new hash) should look like this:

hash1 = { :table => 'first_name', :action => 'view' }

Thanks in advance.

1
  • I don't see any code showing you tried to solve this yourself. Commented Jul 22, 2013 at 13:47

3 Answers 3

1
hash1.each{|k, v| hash1[k] = hash2[v] if hash2.key?(v)}
Sign up to request clarification or add additional context in comments.

Comments

1

I'd write (non-destructive):

hash3 = Hash[hash1.map { |k, v| [k, hash2.fetch(v, v)] }]
#=> {:table=>"first_name", :action=>"view"}

3 Comments

I don't know if the OP really intended this, but the question is asking to destructively modify hash1.
What was wrong with your fetch? I thought it was nice. And now, you need to assume that hash2 does not include a nil or falue value.
@sawa: there you go, fetch again. I cannot seem to make up my mind whether I prefer [k] || v or h.fetch(k, v).
0
hash1 = { :table => 'name', :action => 'view' }
hash2 = { 'name'  => 'first_name', 'group'   => 'user_group' }

hash2.each{|k,v| hash1[hash1.key(k)] = v if hash1.has_value? k}
p hash1
# >> {:table=>"first_name", :action=>"view"}

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.