0
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?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
uzo
  • 2,821
  • 2
  • 25
  • 26

2 Answers2

3

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.

Chuck
  • 234,037
  • 30
  • 302
  • 389
3

By doing the &s, you're telling one_arg that you'd like your Proc s passed as a block (please correct me if I'm wrong). An equivalent writing would be

one_arg(5) do |x|
  x *2
end

There have been a few questions here on SO as of late that deal with this. August Lilleaas has a pretty nice write up about some of the intricacies of all this Ruby madness.

Community
  • 1
  • 1
theIV
  • 25,434
  • 5
  • 54
  • 58