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



Question:

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:1

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.


Solution:2

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »