ClassyPimp
ClassyPimp

Reputation: 725

Ruby array eval as argument to method

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])

Upvotes: 0

Views: 505

Answers (2)

Amit Joki
Amit Joki

Reputation: 59292

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.

Upvotes: 6

Myst
Myst

Reputation: 19221

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.

Upvotes: 0

Related Questions