ruby - 如何使用方法改变局部变量的值?
问题描述
我写了一些代码:
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
解决方案
您无权访问方法中的那些局部变量。
您可以通过传递来玩它,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
参考:
推荐阅读
- swift - Swift 5 Tab View (macOS) 无法确认我给出的宽度
- javascript - 如何通过输入链接从另一个页面复制到我的页面
我想在我的网站上看到
<table class = "plan">
通过我的 css 和 js 代码从学校网站编辑的内容。我试过
<iframe>
了,但这不是我想要的,$ ('# target-div').
Load ('example.com');
但它是:- themes - 如何使用 gatsby-plugin-theme-ui 调整正文背景颜色
- java - 即使缓存被命中,Memcached 也会返回 null
- facebook-graph-api - 如何使用 FB Graph Api (Instagram) 正确过滤嵌套查询?
- nextflow - 如何收集 Nextflow 流程的有序输出?
- html - Css 强制 div 填充它和页脚之间的空间
- c++ - QToolButton 上的文本未绘制
- javascript - 从 Vue 中的子组件获取和设置表单值
- firebase - Flutter http post请求到firebase数据库API导致404