Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Say I have an array. I wish to pass the array to a function. The function, however, expects two arguments. Is there a way to on the fly convert the array into 2 arguments? For example:

a=[0,1,2,3,4]
b=[2,3]
a.slice(b)

Would yield an error in Ruby. I need to input a.slice(b[0],b[1]) I am looking for something more elegant, as in a.slice(foo.bar(b)) Thanks.

share|improve this question

2 Answers

Use this

a.slice(*b)

It's called the splat operator

share|improve this answer
1  
+1: Gaargh! I'm too slow. –  Johnsyweb Feb 19 at 13:47

Using the splat operator:

irb(main):001:0> def fn a, b
irb(main):002:1>   a.to_int + b.to_int
irb(main):003:1> end
=> nil
irb(main):004:0> c = [1, 2]
=> [1, 2]
irb(main):005:0> fn *c
=> 3
share|improve this answer
 
Yes!That's perfect. :) –  Arup Rakshit Feb 19 at 15:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.