Just curious, is there a ruby best practice for effectively passing
parameters by value to protect them from side effects?
I've got a recursive function that modifies a passed in value then
passes that variable to a series of sibling children in turn (where
obviously, it gets further mutated in each). I don't want the changes
to propagate across to the siblings though. Roughly (ignoring return
values and base-case conditions):
def recurse(x = nil)
x = <some processing to reflect current node>
self.children.each do |c|
c.recurse(x) # x will change with each iteration, but don't want that
end
end
I've found that using Object#dup in the method call does work:
c.recurse(x.dup)
But it feels maybe a little hacky. Is there a more accepted form? I
could put the dup into the method definition instead:
def recurse(x = nil)
y = x.dup
y = <some processing to reflect current node>
self.children.each do |c|
c.recurse(y)
end
end
But not sure if that's better or worse or if it even matters. Any thoughts?
Thanks...
-glenn
--
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby