Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace hash value based on the value in another hash

Tags:

ruby

hash

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?

like image 226
Jeff Nyman Avatar asked Feb 07 '26 01:02

Jeff Nyman


1 Answers

You can do this

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

like image 98
rohit89 Avatar answered Feb 09 '26 08:02

rohit89



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!