SpringFlowers AutumnMoon wrote:
> Before, when I say Ruby's reference to an object
>
> a = Car.new
> b = a
>
> i was saying a is a reference to a Car object. and b is now the same
> reference to that object.
>
> I mean it the very traditional pointer way:
>
> int a = 10;
> int *ip, *jp;
> ip = &a;
> jp = ip;
>
> Now I didn't know that, as someone told me, that there is another type
> of reference in C++, Java, and PHP:
>
>
> i = 10
> j =& i
> j = 20
> // and now both i and j are 20 (!!! shocked)
Not so shocking.
int x = 10;
int* p1 = &x;
int* p2 = p1;
*p2 = 5;
cout<<*p1<<" "<<*p2<<endl; //5 5
A C++ reference, which is a different type than a pointer in C++, is
actually implemented as a pointer behind the scenes. However, C++
references allow you to use a different syntax that doesn't require
dereferencing:
int x = 10;
int& r = x; //r becomes a pointer to the same address as x
r = 5;
cout<<x<<" "<<r<<endl; //5 5
In C++, references are sometimes called 'aliases'. But ruby also has
aliases:
x = "hello"
y = x
y[0] = "H"
puts x, y //Hello Hello
In ruby, x and y are aliases for the same object, i.e. both names refer
to the same object, i.e. the object has two different names. The
difference is that the assignment operator is programmed to work
differently in the two languages.
> Isn't that the case? Is the above true so far?
No. java doesn't have pointers, and java does not have the C++
reference syntax:
int num1 = 10;
int num2 = num1;
num2 = 5;
System.out.println(num1); //10
System.out.println(num2); //5
> (and in Ruby, we call a method by "pass by value, the value being the
> reference (pointer) to an object). and when the method returns
> something, it returns a value, which is the reference to an object.) It
> is very consistent all the way.
The key to understanding the difference between pass-by-value and
pass-by-reference, in any language, is understanding that there is no
difference in the passing mechanism. Something is always copied and
sent to the method. In pass-by-value, the value itself is copied and
sent to the method, so if you change the copy from inside the method, it
does not change the original value. In pass-by-reference, the address
is copied, so if you change the value at that address from inside the
method, then the value at that address is permanently changed, and after
the method ends, the change can still be observed.
> In Ruby, we don't have the "alias
> reference", right?
Let's see:
x = "hello"
y = x
y = "goodbye"
puts x, y #hello goodbye
def change_it(num)
num += 1
end
val = 5
change_it(val)
puts val #5
What is your conclusion?
--
Posted via
http://www.ruby-forum.com/.