0

We have method:

def sum(x, y, z)
 x + y + z
end

and array

arr = [1,2,3]

How can one pass the array to sum method? Actually I need something like:

pseudo
sum(arr.each {|i| i})

without changing method, and it to work if sum would accept splat, so please do not offer sum(arr[0], arr[1], arr[2])

2 Answers 2

6

You can use the splat operator * Doing so will automatically assign each value in array to the corresponding named parameter.

sum(*arr)
#=> The above will automagically do
#=> x = arr[0]
#=> y = arr[1]
#=> z = arr[2]

ArgumentError will be raised if more elements are passed.

Sign up to request clarification or add additional context in comments.

3 Comments

cp, if you're not convinced, you can examine sum's parameters with Method#parameters:method(:sum).parameters #=> [[:req, :x], [:req, :y], [:req, :z]]. Note you first need to convert the symbol :sum to a method with Object#method.
"the rest of values in the arr will be ignored, if present" - an ArgumentError is raised if the number of arguments don't match.
Is it only me that thinks the issue is with the #sum method rather then the way it is called?
0

As a global method, you could create a sum method that will accept both numbers and arrays using the * operator:

def sum *numbers
   numbers.flatten.inject :+
end

it will accept:

sum 1,2,3,4
sum [1,2,3,4]
sum [1,2,3,4],[3,4],8,9

The *numbers is an array containing all the arguments passed to the sum method (except a block, which the method doesn't accept). That's what the * operator does.

The #inject method is a really handy shortcut to be used on enumerable objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.