From: 7stud -- Date: 2007-09-29T12:09:28+09:00 Subject: Re: a different type of reference (shocked) 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< 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/.