Path: csiph.com!usenet.pasdenom.info!gegeweb.org!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.ruby Subject: Re: Updating a Hash Value Based On Same-Key in Another Hash Date: Mon, 19 Nov 2012 21:19:54 +0100 Lines: 37 Message-ID: References: <05583123-f97b-49ab-ae03-857af2dcb8fc@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net WHV3QfOd+8g6MEkWH3GBywWbUJpdyOr7ppOBILLgmbHVOXYFA6Z8nDHBDPyQB5UyI= Cancel-Lock: sha1:zLa0aWVeh/HLMO6UPoLomhFxU3s= User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:16.0) Gecko/20121026 Thunderbird/16.0.2 In-Reply-To: <05583123-f97b-49ab-ae03-857af2dcb8fc@googlegroups.com> Xref: csiph.com comp.lang.ruby:6678 On 19.11.2012 16:51, Jeff Nyman wrote: > Hey all. > > I have an issue where I have two hashes. What I'm trying to do is replace a value in the original hash if the second hash has a key matching one of the keys in the first has. To be specific, I have these two hashes: > > data = {"study"=>"Lucid Study", "name"=>"Lucid Plan", "studyWillBe"=>"Combination"} > > conditions = {"study"=>"((current))"} > > What I want to have happen is the data hash should have its "study" key updated since that key is matched in the conditions hash. So I want data to end up like this: > > data = {"study"=>"((current))", "name"=>"Lucid Plan", "studyWillBe"=>"Combination"} > > I'm having a mental block on this. I got this far: > > data = Hash[data.map {|k, v| [conditions[k] || k, v] }] > > But that's not quite doing the trick and I'm finding it hard to get the effect I want. > > Can anyone point me in the right direction? Much appreciated. data.keys.each do |k| conditions.has_key?(k) and data[k] = conditions[k] end keys = data.keys keys.zip(conditions.values_at(*keys)) do |k,v| data[k] = v unless v.nil? end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/