Syntax matters... &args

October 25, 2006 by pedro mota

If the last formal argument of a method is preceeded with an ampersand, a block following the method call will be converted into a Proc object and assigned to the formal parameter.\nIf the last actual argument in a method invocation is a Proc object, you can preceed its name with an ampersand to convert it into a block. The method may then use yield to call it.\n\nsquare = proc { |i| i*i}\n\ndef method1(&b)\n  print, '\\n'\nend\n\ndef method2\n  print yield(8), '\\n'\nend<\n\nmethod1 { |i| i+i } => 18\nmethod2 { |i| i+i } => 16\nmethod2 &square => 64

© 2018 | Follow on Twitter | pedro mg & Hugo