Robert Klemme
5/21/2007 10:57:00 AM
On 21.05.2007 12:41, Erwin Abbott wrote:
> I've written a number of classes which would benefit from the
> Enumerable mixin, but my #each method requires arguments. These are
> usually to specify the range of values, like Fibonacci#each(first,
> last) or whatever. Since Enumerable's #map, #collect, etc don't take
> arguments, how should I proceed? I would be okay with wrapping the
> Enumerable methods I need, but that doesn't seem possible. Do I just
> have to implement my own #map, #to_a, etc?
Just use Enumerator:
12:54:27 [client_1]: irb -r enumerator
irb(main):001:0> class Foo
irb(main):002:1> include Enumerable
irb(main):003:1> def each(a,b,&bl) (a..b).each(&bl); self end
irb(main):004:1> end
=> nil
irb(main):005:0> Foo.new.each(1,5) {|x| p x}
1
2
3
4
5
=> #<Foo:0x7ef7e9b8>
irb(main):006:0> Foo.new.to_enum(:each,1,5).map {|x| x+x}
=> [2, 4, 6, 8, 10]
Btw, is your Foibonacci#each really an instance method or rather a class
method? If it is an instance method you might as well store arguments
in the instance, so you do
Fibonacci.new(1,10).each {|fib| puts fib}
Kind regards
robert