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.

···

--
Posted via http://www.ruby-forum.com/.

You can do this:

def repeat *arg
  arg[0]
end

Regards,
Krishna Aradhi.

···

On Thu, Jun 14, 2012 at 2:32 PM, Michael Sung <lists@ruby-forum.com> wrote:

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.

--
Posted via http://www.ruby-forum.com/\.

Hi,

Michael Sung 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 probably *not* what you want. 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).

--
Posted via http://www.ruby-forum.com/\.

def repeat arg
  arg
end

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

def repeat arg
  arg.dup
end

···

--
Posted via http://www.ruby-forum.com/.

Identity methods always make sense.

···

On Jun 14, 2012, at 2:39, "Jan E." <lists@ruby-forum.com> wrote:

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