2

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]
stevenspiel
  • 5,775
  • 13
  • 60
  • 89
  • what's the reason for the downvote of my question? Is it a bad question? – stevenspiel Dec 31 '13 at 20:21
  • 1
    Looks like someone was running around with a whole bucket of negative votes and didn't realize that for every one they pass out they get one back. I'll bump you up +1. – the Tin Man Dec 31 '13 at 21:47

3 Answers3

5

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
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • 1
    How `arr` will be valid inside a `def` ? `arr` will not be recognized as an local variable to `def add`. – Arup Rakshit Dec 31 '13 at 20:02
  • 2
    In what version of ruby does this work? I get the error: `undefined local variable or method 'arr' for main:Object (NameError)` – Matt Dec 31 '13 at 20:09
  • It's a contrived example... Given the example code, and the problem stated, this is how you would change that code to achieve the desired result. The scope of `arr` is not relevant to this question. – Alex Wayne Dec 31 '13 at 20:11
  • 2
    Worth noting that `#<<` appends while `#+` creates a new array. – jonahb Dec 31 '13 at 22:55
  • @jonahb `<<` appends individual elements. Use `arr += [4,5,6]` to append the whole array. – Matt Jan 01 '14 at 18:43
2

Use concat:

def add(*nums)
  arr.concat nums
end

Or +:

def add(*nums)
  arr + nums
end
Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154
0
$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]
Matt
  • 20,108
  • 1
  • 57
  • 70
  • No, no, no. Don't use a global to solve a simple scope problem. – the Tin Man Dec 31 '13 at 21:45
  • @theTinMan Both the question and the accepted answer *attempt* to use a global, but fail because it is missing the global prefix symbol `$`. This at least shows how to do it correctly in the way the OP desired. Anyways answer is updated to address your comment. – Matt Jan 01 '14 at 00:36
  • 1
    When answering questions, we run into a lot of very bad examples of programming. We don't really serve the person well when we mimic their bad code in our answer; Instead we only perpetuate their lack of knowledge. Instead we should answer their question AND show the right way to do it. It's akin to the idea of giving them fish vs. teaching them how to fish. Show them how to do it correctly all the way around might head off future problems in other areas. – the Tin Man Jan 01 '14 at 04:37