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 the successor of each object, 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. No attempt is made to avoid cycles.

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, the block is converted to a proc and iteration proceeds as in the preceding paragraph.

The return value is not an array, but an Enumerable object that refers to the original objects. In this sense, Object#by is a delegator. Typically, by is used with the for .. in .. construct, or (equivalently) with each, or with collect, select, and so on. In these cases, the dependence on the original sequence does not matter. To get the array of entries produced by by as an independent data structure, use Enumerable#entries or Enumerable#to_a.

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.5

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@users.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 .