I know it is an answer based on my opinion, but this is my preferred way of "trapping" arguments within ruby (without resorting to .dup
or the likes) is to pass them to a function, which passes the arguments to a lambda which is evaluated in place:
def argument_trap(*args)
lambda { args }.call
end
def array_of_three(a, b, c)
a, b, c = argument_trap(a, b, c)
a += 1
b -= 1
c *= 2
[a, b, c]
end
def array_of_n(*args)
args = argument_trap(*args)
args.map { |arg| arg += arg }
end
a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
three = array_of_three(a, b, c)
n = array_of_n(a, b, c, d, e, f)
p [a, b, c]
p three
puts
p [a, b, c, d, e, f]
p n
Gives
[1, 2, 3]
[2, 1, 6]
[1, 2, 3, 4, 5, 6]
[2, 4, 6, 8, 10, 12]
Online demo here
With this pattern it is clear on the first function body line that the argument names are now pointing to clones. But again, this is a matter of preference - i like to keep the original argument names instead of naming them dupA
or something like this, since for me it is clear that within these functions i am working now on duplicates.
This also prevents functions of doing both: working with references to the original value and with duplicates, which in my eyes is an advantage since doing both can lead to a lot of code confusion. On the other hand, one could forget an argument or two, and is again in coding hell..
a.dup
. Speaking for myself, I'm often dissatisfied with whatever I choose. I suggest you try to "Do work ona
,b
,c
that does not mutate those values". If you mustdup
consider doing it "in-line" to avoid the creation of a variable. For example,a.dup.each {...}
.