Paul
Paul

Reputation: 3582

How does the assignment operator work in Ruby?

I'm writing a simple piece of code in ruby, but it's not working the way I expect it to at all. I think this problem comes from a misunderstanding of how ruby works, specifically, how the assignment operator works, relative to other languages. Here's what I've written:

    @instance1 = @clock
    @clock.tick!
    @clock.tick!
    @clock.tick!
    @instance2 = @clock

    puts " instace1.seconds: #{@instance1.seconds}, instance2.seconds: #{@instance2.seconds}"

'Clock' is a class and has a value, seconds, a method 'tick!' which increases seconds by one, and a method 'seconds' which returns the seconds value. Seconds is initalized as 0.

Now when I run this code, the output is: " instace1.seconds: 3, instance2.seconds: 3"

But the output I would expect is: " instance1.seconds: 0, instance2.seconds: 3"

Because, I've assigned intance1 the values which @clock had before I changed clock, and I did nothing to modify @instance1 thereafter.

To me this implies that ruby assigns objects as pointers in some contexts, and that there's implicit dereferencing going on. What are these contexts? (class variables?, large objects? )

How do I make an explicit assignment? In other words, how do I dereference a variable?

Like, in C, I would do something like:

*instance1 = *c

(although it's been a long time since pointer-arithmatic, so that's a rough example

Upvotes: 0

Views: 308

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66867

Ruby assigns by reference, not by value. What you can do is @instance1 = @clock.dup or @instance1 = @clock.clone.

Upvotes: 6

Related Questions