From: Robert Klemme Date: 2007-04-06T19:05:07+09:00 Subject: Re: about functional programming On 06.04.2007 07:11, 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) A straightforward way would be irb(main):001:0> num=(1..10).to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] irb(main):002:0> num.select {|x| x<5}.inject(0) {|sum,x| sum+x} => 10 irb(main):003:0> num.select {|x| x<5}.inject(0) {|sum,x| sum+(x*3)} => 30 irb(main):012:0> num.select {|x| x<5}.map {|x| x*3}.inject(0) {|sum,x| sum+x} => 30 You don't need the "iterator" argument because you typically define these methods in Enumerable. Other than that you can of course combine filter and mapping by mapping values that are not included in the filter to 0: irb(main):004:0> num.inject(0) {|sum,x| sum+(x < 5 ? x*3 : 0)} => 30 As has been pointed out, if you want to define a method "sum" that accepts a filter and a mapping, you would have to provide at least one of the two blocks via proc / lambda. HTH robert