0

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

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

But before you have to make sure that the Clock class implements #dup or #clone. Sadly, Ruby will not do a deep-clone for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.