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?