3

Given two hashes, I'm trying to replace a value in the first hash for a key that the second hash also has. To be specific, I have these two hashes:

data = {
  "study"       => "Lucid Study",
  "name"        => "Lucid Plan",
  "studyWillBe" => "Combination"
}

conditions = { "study" => "((current))" }

I want data to have its "study" key updated since conditions has that key. I want data to end up like this:

data = {
  "study"       => "((current))",
  "name"        => "Lucid Plan",
  "studyWillBe" => "Combination"
}

I got this far:

data = Hash[data.map {|k, v| [conditions[k] || k, v] }]

but that's not quite doing the trick. Can anyone point me in the right direction?

3 Answers 3

4

You can do this

data.each {|k, v| data[k] = conditions[k] if conditions[k]}

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect and does exactly what I need. Thank you very much for the quick response.
2

It's called merge.

data = {"study"=>"Lucid Study", "name"=>"Lucid Plan", "studyWillBe"=>"Combination"}
conditions = {"study"=>"((current))"}

data.merge(conditions)
#{"study"=>"((current))", "name"=>"Lucid Plan", "studyWillBe"=>"Combination"}

1 Comment

This will give wrong result when conditions has a key that data doesn't.
2

The method merge can take a block where you can make some specific operation not only assign new value

data.merge(conditions) do |key, oldvalue, newvalue|
  newvalue
end    
=> {"study"=>"((current))", "name"=>"Lucid Plan", "studyWillBe"=>"Combination"}

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.