Search code examples
rubyproc-objectarity

How can two arguments be passed to a method with a one-argument signature?


s = Proc.new {|x|x*2}

def one_arg(x)
  puts yield(x)
end

one_arg(5, &s)

How does one_arg know about &s?


Solution

  • The & operator turns the Proc into a block, so it becomes a one-argument method with a block (which is called with yield). If you had left off the & so that it passed the Proc directly, you would have gotten an error.