Eric Luo Eric Luo - 6 months ago 9
Ruby Question

Keeping the values of two variables from `each` method

I have the following code:

session={"apple"=>["bp", "80APPM", "donald"]}
@like_list = session
@like_list.each do |key, value|
value.each_with_index do |v, i|
@like_list[key][i] = 2
end
end
session # => {"apple"=>[2, 2, 2]}
@like_list # => {"apple"=>[2, 2, 2]}


The object assigned to the variables
session
and
like
are both changed. Is there any way to perform the above code without changing the value of
session
?

I tried using
clone
and
dup
but no change

Answer

Use the Hash.deep_dup method.

@like_list = session.deep_dup

Here is the documentation for the method

EDIT:

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

require 'active_support'