0

Making a DSL, and I'm just wondering if there's a way to make a method accept an array without placing the array in square brackets.

For example, this works:

def foo args=[]
    args.each { |arg| puts arg }
end
foo ['baz','boo','bing'] #=> 'baz','boo','bing'

But I'd like to be able to hand foo its arguments without the square brackets:

foo 'baz','boo','bing' #=> 'baz','boo','bing'

Not a game changer, just wondering if it can be done :)

2 Answers 2

6

Yes! It's call the "splat" operator. It will take whatever is left over in stuff it in an array.

def foo(*args)
  args.each { |arg| puts arg }
end

> foo 'baz','boo','bing' 
baz
boo
bing
2

You could do it like this with the splat operator

def foo *args
   args.each { |arg| puts arg }
end
foo 'baz','boo','bing' #=> 'baz','boo','bing'

Your Answer

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

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