P
Pedro Silva
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.
I don't know if this will mess things up, but I guess the difference is
only instead of creating a new variable, "tell" the intrepeter to use
the variable passed as argument. But that can break something...
I know the above example can be done like 'a, b = b, a', but this always
obliges to set things directly and never allow to use functions, that,
in my opinion, is a limitation. The actual way forces the programmer to
know if any particular method creates or not a new object. For instance:
def append_str(str, append)
str << append
end
def add_str(str, add)
str += add
end
a = "A"
b = "B"
append_str(a, " + something")
add_str(b, " + nothing")
puts a, b # "A + something", "B"
<< operator changes the object itself so a will be changes, += creates a
new object so b won't be changed. Taking into account that Ruby uses
mainly references for each object (fixnum and company are the
exceptions) I hope this would be possible to include.
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.
I don't know if this will mess things up, but I guess the difference is
only instead of creating a new variable, "tell" the intrepeter to use
the variable passed as argument. But that can break something...
I know the above example can be done like 'a, b = b, a', but this always
obliges to set things directly and never allow to use functions, that,
in my opinion, is a limitation. The actual way forces the programmer to
know if any particular method creates or not a new object. For instance:
def append_str(str, append)
str << append
end
def add_str(str, add)
str += add
end
a = "A"
b = "B"
append_str(a, " + something")
add_str(b, " + nothing")
puts a, b # "A + something", "B"
<< operator changes the object itself so a will be changes, += creates a
new object so b won't be changed. Taking into account that Ruby uses
mainly references for each object (fixnum and company are the
exceptions) I hope this would be possible to include.