Pregunta

say I have

arr = [1,2,3]

How can I change this method so it adds each argument to the array?

def add(*number)
  arr << *number
end

So add(4,5,6) produces:

arr #=> [1,2,3,4,5,6]
¿Fue útil?

Solución

When accepting arguments via splat, they will always be an array. So you can simply add the two arrays together.

def add(*numbers)
  arr + numbers
end

Otros consejos

Use concat:

def add(*nums)
  arr.concat nums
end

Or +:

def add(*nums)
  arr + nums
end
$arr = [1,2,3]

def add(*number)
  $arr.concat number
end

add(4,5,6)

$arr #=> [1,2,3,4,5,6]

Note: concat modifies the object it operates on ($arr). Plus (+) does not.

As the Tin Man mentions, you don't want to use a global to do this. It is better to simply do

arr.concat [4,5,6]

outside of a function call. Better yet:

arr += [4,5,6]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top