私が開発しているRubyアプリケーションがありますが、別のクラスの関数呼び出しから値を返すために内部にブロックを含む再帰関数を使用すると、何らかの理由で期待どおりに機能しません(サンプルコードで見やすくなります)下)。奇妙なことに、何が起こっているのかを調べるために最小限のサンプルを作成したとき、サンプルは期待どおりに機能します。例:
require 'json'
class Simple
    attr_accessor :name, :children
    def initialize(name,children=nil)
        @name = name
        @children = children
    end
end
a = Simple.new('A')
b = Simple.new('B',[a])
c = Simple.new('C',[b])
d = Simple.new('D')
e = Simple.new('E',[d])
f = Simple.new('F')
g = Simple.new('G',[e,f])
foo = [c,e,g]
def looper(d)
    holder = nil
    d.each do |item|
        # puts item.name
        if item.name == 'D'
            holder = Simple.new('Z',[])
        elsif !item.children.nil?
            holder = looper(item.children)
        end
    end
    return holder
end
bar = looper(foo)
puts "Returned from looper: #{bar.name}"
実際のコードでは、クラスインスタンス変数を使用して応答を取得することになりました(これはサンプルコードでも機能します)。上記の関数のスニペットの例を他のパターンに変更しました。
def looper(d)
    holder = nil
    d.each do |item|
        # puts item.name
        if item.name == 'D'
            @holder = Simple.new('Z',[])
        elsif !item.children.nil?
            looper(item.children)
        end
    end
    @holder
end
だから私の質問は、インスタンス変数を使用するのは良い習慣ですか?最初の例のパターンは機能しないのに対し、実際のコードでは機能するので、そうすることの欠点はありますか?