Joel VanderWerf
4/6/2007 5:40:00 AM
gaoxtwarrior wrote:
> when it comes the method needs two block to accomplish a task,how the ruby
> do which? for example , the classical sum(filter,mapping,iterator)(I have
> forgotten the style, maybe,the one can search it in SICP)
If the two blocks are applied sequentially, as part of two separate
iterations, it's straightforward:
[1,2,"fred","wilma",5,6].select{|x|x.kind_of?(Numeric)}.inject{|s,x|s+x}
=> 14
In this special case, we can use #grep because testing for
x.kind_of?(Numeric) is the same as testing Numeric === x (which is what
grep(Numeric) does):
[1,2,"fred","wilma",5,6].grep(Numeric).inject{|s,x|s+x}
=> 14
More generally, though, the only way to pass more than one block to a
method is to turn all but one of the blocks into procs, like this:
meth_with_two_blocks(proc {...}) { ... }
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407