Skip to content

Instantly share code, notes, and snippets.

@chrisseaton
Last active January 4, 2016 16:29
Show Gist options
  • Save chrisseaton/8648164 to your computer and use it in GitHub Desktop.
Save chrisseaton/8648164 to your computer and use it in GitHub Desktop.
def foo(*a)
# Isn't the * below redundant? Doesn't it cast a to an Array if it isn't one already?
# But if you remove it the behaviour changes - how come?
yield *a
end
puts foo(1, 2) { |a| a }
# MRI, JRuby, prints 1; Truffle prints 1 2
@enebo
Copy link

enebo commented Jan 27, 2014

I think this will make the example a little more clear:

def foo(*a)
  yield a
  yield *a
end

foo(1, 2) { |a| p a }

In the first yield we are passing a single argument which is an array. Since the block accepts a single arg you get the whole array.

In the second yield you splatted the array back as two arguments to the yield. Since the block accepts a single arg you get the first element.

block argument passing is easily the most confusing part of Ruby...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment