Loser question

I have a lot of functions that do things like this:

I have a function that takes an array, and sets various additional
"default' values in it. I first clone what is passed in:

   newvals = args.clone

and then modify newvals.

I assume .dup and .clone are about the same?

--Michael

I would say that it depends on the context. If this is something you
will do often, make a function out of it to keep things DRY, but if it's
just once or twice , do it inline. Since we are not talking about a
large number of lines of code and the intent is fairly obvious, it
really doesn't matter too much.

my $.02
-Bill

Michael Graff wrote:

I'm not quite sure what you're driving at here. Were you expecting
different behavior than what you showed in your original post? I mean,
if h and g are references to the same object, of course modifying the
object will have a same result no matter which reference you use to
"view" the object.

If your end goal is to create references to two different objects (by
object identity) that begin life with the same contents, then it's
very common in object oriented programming languages to clone (dup)
the object. Any other behavior than this would be "odd" at best, and
would completely confuse every object oriented programmer out there.

Here is an example of how a language other than Ruby would support
this. The following is a "factory" method used to construct a new
array using the contents of another array written in Objective C:

+ (id)arrayWithArray:(NSArray *)anArray

Here the + indicates that this is a class method returning an array
constructed using a reference to a different array. The array returned
by this method references an new array and does not simply reference
the original array.

Ruby doesn't actually have this type of factory method, but if you do
this a lot it could be easily added to the Array class. But, is that
really worth it when all you need is:

g = h.dup