首页 > 解决方案 > 如何使用方法改变局部变量的值?

问题描述

我写了一些代码:

a = 4
b = 7
def swaps(g, f)
  g ^= f; f ^= g; g ^= f
end

swaps(a, b)
p a, b

我以为我想要结果:a 值为 7,b 值为 4,但我得到了结果:

4, 7

标签: rubyvariablesbinding

解决方案


您无权访问方法中的那些局部变量。

您可以通过传递来玩它,binding但这不应该在现实生活中使用:

类的对象Binding将执行上下文封装在代码中的某个特定位置,并保留此上下文以供将来使用。

def change(local_variable_name, binding, new_value)
  binding.local_variable_set(local_variable_name, v)
end

测试:

a = 1

a                      #=> 1
change(:a, binding, 2) #=> 2
a                      #=> 2

你的情况:

def swap(first, second, binding)
  old_first  = binding.local_variable_get(first)
  old_second = binding.local_variable_get(second)

  binding.local_variable_set(first, old_second)
  binding.local_variable_set(second, old_first)
end

a = 1
b = 2
swap(:a, :b, binding)
a #=> 2
b #=> 1

参考:


推荐阅读