[^]EachDelegator

Japanese Document.

[^]eachdelegator.rb

all Enumerable library.

Version 0.1.3

Copyright(c) 2001
Okada -yun- Jun
yun@nekome.net
http://www.nekome.net/ruby/index_en.html

[^]What's EachDelegator?

EachDelegator is a library, to add Enumerable capability to a existing method, which takes block as argument (namely iterator!).

In ruby, there are classes, which have several methods named 'each_*'. for exapmple, String have both 'each_line' and 'each_byte'.

In such a class, I have a desire to apply Enumerable methods to these methods, but I couldn't. 'each' is a only method, who is interface for Enumerable.

Behind such a background, I've written this library.

[^]How to use?

[^]Simple usage.

After required 'eachdelegator.rb', all methods named 'each_*' or '*_each' is automatically redifined to be able to call Enumerabele methods.

enumdelegator.rb redefine these methods to return EachDelegator object when they are called without block.

EachDelegator is a Enumerable class, that delegates its each method to orignal object's original method. When you call Enumerable methods (e.g. collect, grep), these result is apply to original method like 'each' method.

For example, call String#each_byte with index, and collect the result. This complex process is written in such a simple form.

  p "hoge".each_byte.each_with_index.collect{|a, i| [ i, a ]}
   => [[0, 104], [1, 111], [2, 103], [3, 101]]

[^]Advanecd usage.

Only 'each_*' or '*_each' methods are automatically redefined. If you want to apply EachDelegator's effect to a method not named 'each_*' or '*_each', you can manually do it with Module#each_delegator.

For example, when define Array#all_pair which iterate all adjacent pairs, and apply EachDelegator's effect to the method, write as following form.

  require 'eachdelegator'

class Array def all_pair for i in 0...(size - 1) yield at(i), at(i + 1) end self end

each_delegator :all_pair end

p [1, 3, 5, 7, 13].all_pair.collect{|a, b| b - a} => [ 2, 2, 2, 6]

[^]History

[^]2000/1/23 version 0.1.3

rename EnumDelegator to EachDelegator

add methods named '*_each' to auto redefinition target.

[^]2001/1/22 version 0.1.2

modified Module#method_added to trace method definition of 'each_*' and redefine it automatically, after required 'enumdelegator.rb',

[^]2001/1/21 version 0.1.1

modified enum_delegator to be able to handle methods which takes arguments excepting block.

[^]2001/1/20 version 0.1.0

first release.