tags:

views:

36

answers:

1
s = Proc.new {|x|x*2}
puts s.call(5)
-> 10

def foo(&a)
 a.call(5)
end

puts "test foo:"
foo(s)

When I try to call the proc above, I get:

foo: wrong number of arguments (1 for 0) (ArgumentError)

My expectation was that I can pass a proc to a method if the method is defined with this type of signature:

def foo(&a)

and then I can execute the proc insiide foo like this:

 a.call(5)
+7  A: 

If you want to pass an actual proc to foo, just define it with def foo(a). Putting the & in front of a means "this isn't actually an argument. Instead take the block passed to this method, create a proc out of it, and store that proc in the variable a". In other words with your current definition you can call foo like this:

foo do |x|
  puts x*2
end

You can also use & when calling a method to turn a proc into a block:

foo(&s)
sepp2k
glenn jackman