Gregory Seidman
9/6/2008 5:20:00 PM
On Sat, Sep 06, 2008 at 08:59:01AM +0900, Pedro Silva wrote:
> Would be possible to include the option to pass arguments by reference
> instead of by value?
>
> def swap(a, b)
> tmp = a
> a = b
> b = a
> end
>
> a = "A"
> b = "B"
> swap(a, b)
> puts a, b # "A", "B"
>
> Because Ruby passes arguments by value any attribution will change only
> the arguments not the variables. My sugestion is to use some way of
> indicating that the argument is a reference and that would allow the
> above example to work.
[...]
First off, you're talking about a rare need. It's generally poor practice
to add syntax to serve a rare need. Instead, you need an idiom to take care
of it on the rare occasions when you need it. For your simple swap example
above, the idiom doesn't even involve a function:
a,b = b,a
That uses an implicit array. For more complex examples you use an explicit
array:
def increment_values(values)
values.map! { |v| v.succ }
end
a = 1
b = 2
c = 3
foo = [ a, b, c ]
increment_values(foo)
a,b,c = foo
Given the acceptable ease with which you can fulfill your rare pass by
reference needs with existing syntax, the marginal additional value of
simpler syntax is overwhelmed by the marginal additional complexity such
syntax requires.
--Greg