可变范围和修改

时间:2015-09-01 18:08:13

标签: ruby

为什么调用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}"

2 个答案:

答案 0 :(得分:1)

Ruby是按值传递(Is Ruby pass by reference or by value?),所以你绝对可以修改对象的值,你会在方法之外看到它的效果。

考虑这些:

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

以上所有修改参数。

答案 1 :(得分:-1)

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