如何在 ruby proc/lambda 中使用真正的局部变量 [英] how to use truly local variables in ruby proc/lambda
问题描述
初学者 Ruby 问题.更改此代码的最简单方法是什么,但保持块完全完整,从而消除副作用?
Beginner Ruby question. What is the simplest way to change this code, but leaving the block completely intact, that eliminates the side effect?
x = lambda { |v| x = 2 ; v}
x.call(3)
#=> 3
x
#=> 2
这是我能想出的最简单的例子来说明我的问题,所以删除分配"或不将 Proc 分配给 x"不是我想要的.
This is the simplest example I could contrive to illustrate my issue, so "remove the assignment" or "don't assign the Proc to x" is not what I'm looking for.
我想在 Proc(或 lambda)中设置局部变量,该变量可以在不影响原始封闭范围的情况下进行分配.我可以动态创建一个类或模块来包装块,但这对于这样一个基本的东西来说似乎有点过分.
I want to set local variables in a Proc (or lambda) that can be assigned without affecting the original enclosing scope. I could dynamically create a class or module to wrap the block, but that seems overkill for such a basic thing.
与我正在尝试做的等效的 Python:
Equivalent Python to what I'm trying to do:
def x(v):
x = 2 # this is a local variable, what a concept
return v
推荐答案
有时这是期望的行为:
total = 0
(1..10).each{|x| total += x}
puts total
但有时它是偶然的,您不想弄乱碰巧具有相同名称的外部变量.在这种情况下,在参数列表后面加上分号和块局部变量列表:
But sometimes it's accidental and you don't want to mess with an outside variable which happens to have the same name. In that case, follow the list of parameters with a semicolon and a list of the block-local variables:
x = lambda{|v; x| x = 2; v}
p x.call(3) #3
p x #<Proc:0x83f7570@test1.rb:2 (lambda)>
这篇关于如何在 ruby proc/lambda 中使用真正的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!