class Object

instance method

Object#by next_spec = nil, *args, &next_proc

Allows use of Enumerable methods, such as each, collect, select, etc., to iterate over arbitrary objects. The caller supplies a way of calculating each object from its predecessor, such as an accessor method for the next element of a linked list.

Object#by returns an Enumerable object whose each method iterates over the sequence beginning with self and continuing as specified by the arguments. Only the current element of the sequence is kept in memory.

If next_spec is a string or symbol, next_proc is ignored and next_spec is treated as a method name. This method name is sent, along with arguments args, to each element of the sequence to generate the next element. The sequence terminates at the first element for which the method returns nil or false.

If next_spec is anything else, except nil, next_proc is ignored and next_spec is required to be an object that responds to [], such as a proc or a hash. The [] method of next_spec is called with each element of the sequence in turn as an argument, along with args, to generate the next element. The sequence terminates at the first element for which [] returns nil or false.

If next_spec is not given, or is nil, a block is required. In this case, iteration proceeds as in the preceding paragraph.

examples

require 'enum/by'

class A; end
class B < A; end
class C < B; end

for cl in C.by :superclass
  print cl, " "
end

# prints: C B A Object

steps = proc { |x, incr, limit| y = x + incr; y <= limit ? y : nil }
p 0.by(steps, 10, 50).to_a

# prints: [0, 10, 20, 30, 40, 50]

See the end of the source file for more examples.

version

Enumerable tools 1.1

The current version of this software can be found at http://redshift.sourceforge.net/enum .

license

This software is distributed under the Ruby license. See http://www.ruby-lang.org.

author

Joel VanderWerf, vjoel@sourceforge.net

acknowledgement

Thanks to David Alan Black for his helpful comments on the Ruby mailing list http://blade.nagaokaut.ac.jp/ruby/ruby-talk .