[ next ] [ prev ] [ contents ] [ up to Understanding Blocks ] Using Ruby

Iterators

class Trio
  include Enumerable
  def initialize(a, b, c)
    @items = [a, b, c]
  end
  def each
    @items.each { |item| yield item }
  end
end

t = Trio.new('x', 'y', 'z')
t.each { |item| puts item }
p t.collect { |item| item.upcase }
p t.select { |item| item =~ /[xz]/ }
p t.reject { |item| item =~ /[xz]/ }
p t.find   { |item| item =~ /[yz]/ }
p t.inject('') { |item, sum| sum + item }
p t.grep(/[z]/) 

Output

x
y
z
["X", "Y", "Z"]
["x", "z"]
["y"]
"y"
"zyx"
["z"]



[ next ] [ prev ] [ contents ] [ up to Understanding Blocks ] Copyright 2003 by Jim Weirich.
Some Rights Reserved