Simple method & array question

Hi,

Sorry for the newbie question but how can I make a method which takes
only an array as an argument and returns the same array as the output?

For example, I tried:

def repeat *arg
repeated = *arg
p repeated
end

repeat [10, 2, 2, 54]

However, this returns: [[10, 2, 2, 54]]

when I would really just like the same array repeated back: [10, 2, 2,
54]

Thank you.

You can do this:

def repeat *arg
arg[0]
end

Regards,
Krishna A…

Hi,

Michael S. wrote in post #1064551:

For example, I tried:

def repeat *arg
repeated = *arg
p repeated
end

Why are you using *arg? This will take all the arguments of the method
call (there may be any number) and put them into an array, which is
referenced by arg.

For example:

#-------------------------
def f *args
puts “args is #{args.inspect}”
end

f(1, 2, 3) # args is [1, 2, 3]
f(“a”) # args is [“a”]
f() # args is []
#-------------------------

This is obviously not what you want, because it will wrap the array
into another array and allows additional arguments. You rather want the
method to take a single argument (the array) and return this argument:

#-------------------------
def repeat array
array
end
#-------------------------

Of course this method doesn’t make sense (and it works not only for
arrays but every object).

On Jun 14, 2012, at 2:39, “Jan E.” [email protected] wrote:

Of course this method doesn’t make sense (and it works not only for
arrays but every object).

Identity methods always make sense.

def repeat arg
arg
end

or if you want a copy of the array and not the original

def repeat arg
arg.dup
end