Category talk:Ruby

From Rosetta Code
Revision as of 02:03, 10 July 2011 by 189.104.25.246 (talk)

Pass by reference?

How is Ruby pass-by-reference? The passing of values in Ruby (which are all references) has exactly the same semantics as the passing of reference type values in Java. (Is it not?) Java is listed as pass-by-value only. So to be consistent we should list Ruby as pass-by-value. --76.91.63.71 20:02, 2 August 2009 (UTC)

Ruby is pass-by-value as you say. I changed the page from 'parampass=reference' to 'parampass=value'. I also changed it from 'execution=bytecode' to 'execution=interpreted'. Ruby 1.9 compiles a program to bytecode and executes the bytecode, but this is an internal detail of the interpreter. There is no Java .class or Python .pyc file. --Kernigh 01:44, 9 March 2011 (UTC)

This program shows that Ruby passes by value:

<lang ruby># Ruby def f(x)

 x = "different string"

end

x = "original string" f(x) puts x # => "original string"</lang>

If Ruby would pass by reference, then this program would print "different string". But it prints "original string", because the two x have distinct values. Contrast Perl, which passes by reference:

<lang perl># Perl sub f {

 $_[0] = "different string";

}

my $x = "original string"; f($x); print "$x\n"; # => "different string"</lang>

This program prints "different string" because Perl passes $x by reference, so $_[0] is an alias of $x. (Many Perl subs use my $x = shift; to create a distinct value.)

Ruby would act like Perl if the Ruby program would use x.replace "different string". This would work because x is a reference to a mutable string. I think that Ruby is pass by value because I can use assignment to change the value of x, to refer to some other string. I am reverting the page to 'parampass=value', after 74.215.210.198 reverted the page to 'parampass=reference', after I changed it to 'parampass=value'. --Kernigh 02:31, 16 March 2011 (UTC)


Ruby passes by reference since it don't make copies of the objects when passing then to a method. Look:

<lang ruby>def f(x)

 x.replace("different string")
 x << " from method"
 x = "another variable"

end

x = "original string" f(x) puts x # => "different string from method"</lang>

All variables are, internally, pointers to objects, so, when I pass the variable, it passes the reference to the object, that allow me to change directly the object. But I can't set the variable because when you set it inside the method you are creating another variable that have nothing to do with the old one. I'm reversing the change on "parampass", to 'reference'.

189.104.25.246 02:03, 10 July 2011 (UTC)