Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
var関数の実行後に、次のコードで関数に渡される変数が変更されるのはなぜですか?
var
def my_func(my_var) out_var = my_var out_var[3]="STUFF" return out_var end var = "Testing" puts my_func(var) puts var
出力:
TesSTUFFing TesSTUFFing
なぜ「var」が変更されたのですか?誰かが私にこれを説明してもらえますか?
Rubyでは、変数は参照によって渡されます。
変数を明示的に複製する必要があります。
def my_func(my_var) out_var = my_var.clone out_var[3]="STUFF" out_var end
文字列はRubyで不変ではないため、文字列を変更する関数に文字列を渡すことができます。