Catching a variable for later use in Ruby
I am relatively new to Ruby, but I am trying to catch a variable for later use.
Example:
x = [1,2,3]
y = x
y.reverse!
How do I get the original value of x back? It looks like x got changed when I changed y. Basically I need to catch and 开发者_开发百科hold a variable value while altering a copy of it. Many thanks! AlanR
A number of "mutating!" methods are paired with an equivalent non-mutating form. (Generally, if such a pair exists, the non-mutating form lacks the trailing !
in the name.)
In this case, and in every case unless there is a good reason to justify otherwise, I recommend using the non-mutating form. I find that reducing side-effects makes code cleaner and also reduces subtle little issues like this. (gsub!
can be particularly icky.)
>> x = [1,2,3]
=> [1, 2, 3]
>> y = x
=> [1, 2, 3]
>> y = y.reverse
=> [3, 2, 1]
>> x
=> [1, 2, 3]
Happy coding.
You need to use .dup
to create a clone of x.
x = [1,2,3]
y = x.dup
y
I agree with pst, it's bad style to mutate the original object rather than using a functional expression to create a new and modified version.
y = x.reverse # problem solved
精彩评论