我曾经用词法范围编写类似 let 的表达式。
所以我写了自己的(很遗憾,但它会因多个线程而失败):
# Useful thing for replacing a value of
# variable only for one block of code.
# Maybe such thing already exist, I just not found it.
def with(dict, &block)
old_values = {}
# replace by new
dict.each_pair do |key, value|
key = "@#{key}"
old_values[key] = instance_variable_get key
instance_variable_set key, value
end
block.call
# replace by old
old_values.each_pair do |key, value|
instance_variable_set key, value
end
end
我在谷歌搜索红宝石的这种结构(可能是额外的块定义),但找不到。也许我失去了一些东西?在这种情况下,人们使用什么红宝石?
PS:对不起,我的英语不好,你知道的。
UPD:我想提供使用示例:
@inst_var = 1
with :inst_var => 2 do
puts @inst_var
end
puts @inst_var
输出:
2
1