AlanR
AlanR

Reputation: 23

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

Upvotes: 2

Views: 104

Answers (3)

DigitalRoss
DigitalRoss

Reputation: 146123

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

Upvotes: 4

user166390
user166390

Reputation:

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.

Upvotes: 6

Dogbert
Dogbert

Reputation: 222248

You need to use .dup to create a clone of x.

x = [1,2,3]
y = x.dup
y

Upvotes: 4

Related Questions