user1526546
user1526546

Reputation:

ruby pass-by-reference vs pass-reference-by-value

Coming from a heavy C++ background, I am having a hard time understanding how ruby function parameters are passed, or rather, I am having difficulty understanding the difference in semantics between pass-by-reference and pass-reference-by-value which seems to be the distinction that is made in the ruby community. There are many resources with conflicting information on the subject (including this site, which I have posted below and responses seem to differ greatly).

Is Ruby pass by reference or by value?

My confusion is that in C++ pass-by-reference:

int function(Object& i)
{
    //cannot change the memory location of i in this function

    //only the value can change
    Object.param1 = 3;
}

or pass-by-pointer:

int function(Object* i)
{ 
    //this change will be visible in the calling function scope
    Object->param1 = 4;

    //this however will have no effect from the calling code
    i = new Object(); 
}

In both these cases it seems to me that the values contained with an Object can change; however, the reference/pointer to it cannot. Yet I see people draw the distinction between pass-by-reference and pass-reference-by-value based on the fact that you cannot change the what the reference is pointing to. However, given that you cannot do that without a pointer to a pointer, I do not understand why this distinction is made.

It seems to me that Ruby behaves in the same manner:

class TestObject
    attr_accessor :param1

    def initialize()
        @param1 = 0
    end
end

def func(objtst)
    objtst.param1 = 12
end

obj_test = TestObject.new
puts obj_test.param1 #outputs 0
func(obj_test)
puts obj_test.param1 #now outputs 12

So what is the distinction between pass-by-reference and pass-value-by-reference?

Upvotes: 2

Views: 970

Answers (1)

newacct
newacct

Reputation: 122439

I do not understand why this distinction is made.

This distinction is the essence of pass-by-reference. In your first function, you can do a simple assignment to the parameter: i = something, and it will do the same thing as an assignment in the calling scope. In your second function, i = something can never have an effect on the calling scope. In fact, there is nothing that you can do inside the second function that has the exact same semantics as assigning to the variable in the calling scope. That's it. That's the distinction.

In Ruby (as well as Python, Java, and many other languages), assigning to a parameter variable (with =) never has an effect on the calling scope. Hence, they are pass by value.

Upvotes: 2

Related Questions