From: Shin-ichiro Hara Date: 1999-03-11T23:51:12+09:00 Subject: [ruby-dev:6232] Re: Incrementable 原です。 こういうものの tree の探索との相性はどうかと思ったのですが、 class RecursiveArray include Incrementable class Node attr_accessor :body, :succ def initialize(body); @body = body; end end def initialize(array) @root = Node.new(array) mk_tree(array, @root) end def mk_tree(array, root) if array.is_a? Array prev = nil array.each do |x| n = Node.new(x) if prev prev.succ = n else root.succ = n end prev = mk_tree(x, n) end prev else root end end def leaf?; not @root.body.is_a?(Array); end def status; @root; end def inc; @root = @root.succ; end def inspect; @root.body.inspect; end end b = RecursiveArray.new([1,[2,[3,[4,5]]], [6,[7,8], [[9], 10]]]) b.start do |x| p x if x.leaf? #=> 1, 2, ..., 10 end アルゴリズムが難し過ぎ。(^^; いきなり RecursiveArray#each を書き下した方が楽でした。 class Array def each1(&block) each do |x| block.call(x) x.each1(&block) if x.is_a? Array end end end [1,[2,[3,[4,5]]], [6,[7,8], [[9], 10]]].each1 { |x| p x unless x.is_a? Array } これでほぼ同等ですからね。