From: Watanabe Keiji Date: 2006-09-24T01:54:09+09:00 Subject: [ruby-list:42826] Re: 再帰呼び出しの深さを知りたい わたなべです。 2006/09/24 1:15:46 Hideo Konami wrote. and reply message: > 次のサンプルのような再帰的な構造(実際に扱いたいのはツリー)で, > どのレベルまで下がっているのか,つまりパスの深さを得たいので > す。うまい方法はないものでしょうか。グローバル変数を使わないで, > 入れ子になった構造の深さが分かるとうれしいのですが こんな感じでいかがでしょうか。 class Link def initialize() @son = nil end def add if @son then @son.add else @son = Link.new end end def get_depth(depth = 1) if @son then @son.get_depth(depth + 1) else depth end end end h = Link.new print "#{h.get_depth}\n" # --> 1 h.add print "#{h.get_depth}\n" # --> 2 h.add print "#{h.get_depth}\n" # --> 3 -- Watanabe Keiji - k@elt.ne.jp