Eric Luo Eric Luo - 2 years ago 59
Ruby Question

Ruby keeping the values of two variables from .each method

I am a newbie in Ruby. I have the following code:

irb(main):137:0> session={"apple"=>["bp", "80APPM", "donald"]}
=> {"apple"=>["bp", "80APPM", "donald"]}
irb(main):138:0> @like_list = session
=> {"apple"=>["bp", "80APPM", "donald"]}
irb(main):139:0> @like_list.each do |key, value|
irb(main):140:1* value.each_with_index do |v, i|
irb(main):141:2* @like_list[key][i] = 2
irb(main):142:2> end
irb(main):143:1> end
=> {"apple"=>[2, 2, 2]}
irb(main):144:0> session
=> {"apple"=>[2, 2, 2]}
irb(main):145:0> @like_list
=> {"apple"=>[2, 2, 2]}

The method ".each" seems to change the content of the object assigned by both variable 'session' and 'like', and thus both variable values changed.

Is there any way to perform the above code without changing the value of 'session'?

I have tried using .clone and .dup but no change

Answer Source

Use the Hash.deep_dup method.

@like_list = session.deep_dup

Here is the documentation for the method


If you are not using Rails, you need to load activesupport:

require 'active_support'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download