The method in question that I want to use is gem and sourced here (lines 17-42): https://github.com/rails/rails/blob/master/railties/lib/rails/generators/actions.rb
As you can see, name is assigned to the first arg on line 19, then message is assigned to name on line 23 and finally message is mutated on line 26 with <<. This unfortunately means that the string I am passing in as the first argument is mutated outside of the method.
I have a hash of arrays and am iterating over them as follows:
groups = { foo: %w(foo, bar), bar: %w(foobar) }
groups.each do |group, gems|
gems.each do |name|
gem(name, "42")
end
end
Afterwards my hash looks like this due to the mutation inside of gem:
groups => { foo: ["foo (42)", "bar (42)"], bar: ["foobar (42)"] }
How can I prevent these strings (and the hash and its arrays) from being mutated but without breaking the method?
You may call it with
name.dup:Background: With
gem(name)you pass the parameter to the method. Any modification inside the called method, will change also the the original variable.With
name.dupyou make a copy of the object. This copy is modified inside the called method, but the original value is unchanged.A warning:
dupdoes not work always, it is depending on the data.dupdoesn’t make a deep copy. See this example:Explanation: The array
arris copied, but not the content inside the array.Inside the
mapyou modify the data of the copied array. But the elements of the original and the copied array are the same. So you also change the content of the original array.