From: "W. Kent Starr" Date: 2002-12-27T19:11:05+09:00 Subject: Re: viral arguments On Fri, 2002-12-27 at 03:12, Tom Sawyer wrote: > the idea is that rather then pass simple argumments, one could pass a little > piece of code that would execute in the context of the method. > > here's a foo example (vproc is like proc but viral): > > def foo(x) > i = 1 > puts "#{x + i}" > end > > puts foo(4) --> 5 > puts foo(vproc {i + 1}) --> 3 > > any thoughts? can ruby achieve something like this already? > If I am understanding you correctly, Ruby has this mechanism already. It is called a "block" (much better sounding than "viral" is it not?) def foo (x=nil) i = 1 x = 0 if !x # use whatever default you want, or raise error return yield (i) if block_given? i + n end bar = Proc.new { |i| i + 3 } baz = Proc.new { |i| i * 5 } foo #=> 1 foo 4 #=> 5 foo &bar #=> 4 foo &baz #=> 5 Thus, no argument returns a predefined default Argument returns defined behavior operating on argument Block returns returns operation on variable i Note & in front of block names (bar and baz); this tells Ruby a block has been passed (given). The block_given? method in the if statement tests for that. This is a very powerful feature; there are a lot of possibilities. Play araound, experiement and enjoy. Hope this helps? Regards, Kent Starr