I’ve been expermenting with ruby for sometime now, and I’m really enjoying it, and I’m now coping with ‘#’ comments 🙂
Now one of the points that’s about functions, is how do they pass, by value, or by reference. So to try out Ruby.
#!/usr/bin/env ruby
def changeValue(x)
x = 10
end
y = 5
p y
p changeValue(y)
p y
The output would be:
5 10 5
So, we can assume that the call is by value, but wait if you try the code
#!/usr/bin/env ruby
def changeValueStr(str)
str[0] = 'H'
str
end
y = 5
s = 'Foo'
p s
p changeValueStr(s)
p s
The output would be:
"Foo" "Hoo" "Hoo"
Mmm, the value did change, so is it by reference?
Well, actually the calls are by Handle, (or what C/C++ Developers call By Pointer). It’s the same as passing by value, but instead of passing the value of the object itself, it pass the value of the pointer that holds the actual object.
And for ruby, as everything is an object, it’s always passed by handle.
So in the first case, we are sending the value of the pointer to the function “changeValue”, and putting it in the local variable x, making x pointing to the original object, but then, we assign the local variable x to a new object, leaving the first one intact.
To translate it to the C pointers, the code would be.
#include <stdio.h>
void changeValue(int* ptr) {
*ptr = 10;
}
void notChangeValue(int* ptr) {
int y = 5;
ptr = &y;
}
int main() {
int myInt = 15;
int* intPtr = &myInt;
printf("%d\n",*intPtr);
changeValue(intPtr);
printf("%d\n",*intPtr);
notChangeValue(intPtr);
printf("%d\n",*intPtr);
return 0;
}
if you compile it and run it, you would see the output as
15 10 10
I guess, it might be clearer.
For PHP 5, the same holds for objects (not anything else), I mentioned that while talking about The Value Design Pattern, but to show it here, the code will be something like.
<?php
class MyClass {
public $x;
function __construct($v) {
$this->x = $v;
}
}
function changeClass(MyClass $c) {
$c->x = 10;
}
function notChange(MyClass $c) {
$c = new MyClass(5);
}
$c = new MyClass(15);
echo $c->x . PHP_EOL;
changeClass($c);
echo $c->x . PHP_EOL;
notChange($c);
echo $c->x . PHP_EOL;
And ofcourse the output would be:
15 10 10
Hope it was useful, and Happy Coding.