2012-01-15 7 views
3

は、どのように私は内部のメソッド外で変数にアクセスすることができますし、どのように私は、メソッドのプロトタイプを宣言することができ、ここでアクセスメソッド内のローカル変数

debug = false 
debug_file = "debug.txt" 
terminate_tool 

def terminate_tool 
    info_string = "Terminating tool execution ...\n" 
    print info_string 
    File.open(debug_file, "a") { |file| file.print info_string } if debug 
end 

..私が何をしようとしていますどのようなサンプルコードです私はその定義を最後に書きたいのですから?

答えて

0

インスタンス変数を使用して、メソッドの外部で変数を使用することで実現できます。

def terminate_tool 
    p @debug_file # "debug.txt" 
end 

@debug_file = "debug.txt"  
terminate_tool 

私はそれをメソッドに渡すことをお勧めします。

def terminate_tool(debug_file) 
    p debug_file # "debug.txt" 
end 

terminate_tool("debug.txt") 

あなたの最終目標が最小限のコードサンプルで与えられているかどうかはわかりません。しかし、procs、ブロック、lambdasについて読むことは役に立つかもしれません。 http://innig.net/software/ruby/closures-in-ruby.html

例外として、インスタンス変数はクラスのインスタンスには渡されません。

def terminate_tool 
    p @debug_file # "debug.txt" 
end 

class A 
    def foo 
    p @debug_file # nil 
    end 
end 

@debug_file = "debug.txt" 
terminate_tool 

a = A.new 
a.foo 
関連する問題