可变范围和修改

为什么调用mess_with_vars方法不会修改其中显示的变量的值?

 def mess_with_vars(one, two, three) one = "two" two = "three" three = "one" end one = "one" two = "two" three = "three" mess_with_vars(one, two, three) puts "one is: #{one}" puts "two is: #{two}" puts "three is: #{three}" 

Ruby是按值传递 ( Ruby是通过引用还是通过值传递? ),因此您可以明确地修改对象的值,并且您将在方法之外看到它的效果。

考虑这些:

 def mess_with_vars(one, two, three) one.gsub!('one','two') two.delete!("wo") three.replace "one" end 

以上都修改了参数。

因为在方法定义中初始化的局部变量的范围是方法定义。