Ruby学習中

Rubyクックブック ―エキスパートのための応用レシピ集

Rubyクックブック ―エキスパートのための応用レシピ集

じょびっとアレンジ。

class Tree
  attr_reader :value
  include Enumerable
  
  def initialize(value)
    @value = value
    @children = []
  end
  
  def <<(value)
    subtree = Tree.new(value)
    @children << subtree
    subtree
  end
  
  def each
    yield value
    @children.each do |node|
      node.each{ |e| yield e}
    end
  end
end

root = Tree.new(1)
child1 = root <<  10
child1 << 20
child1 << 30
child2 = root << 50
child2 << 60

root.each{ |x| puts x} 
root.max # => 60 
root.min # => 1
root.find_all {|x| x > 40} # => [50, 60]
root.map{|x| x * x } # =>  [1, 100, 400, 900, 2500, 3600]


追記
http://www.oreilly.co.jp/books/9784873113241/rc_dif.html
同じ職場の人に教えてもらった。約半分削られてるんだ。ちょこっとショック。