编写闭包的正确方法是什么?
我有一个值 X。稍后我会使用这个值。我实际上并不关心该值是什么,但一段时间后我会得到另一个值 Y,我想知道是否 X == Y。
此类数据的一种方法是创建一个像这样的闭包:
def createExactMatchClosure(str)
return lambda { |t|
return str == t
}
end
保存 我可以使用此代码来测试另一个变量是否等于我原来的变量:
myOriginalValue = "hello"
testerFunction = createExactMatchClosure(myOriginalValue)
puts testerFunction.call("hello").to_s # prints true
我的问题是,以下内容是否更好/更差/不同?我在教程中看到过这两种方法。
def createExactMatchClosure(str)
string_to_test = str
return lambda { |t|
return string_to_test == t
}
end
I have a value X. I will use this value some time later on. I don't actually care what the value is, but some time later I will get another value Y, and I Want to know if X == Y.
One way to hold this sort of data is to create a closure like this:
def createExactMatchClosure(str)
return lambda { |t|
return str == t
}
end
Now I can use this code to test if another variable equals my original one:
myOriginalValue = "hello"
testerFunction = createExactMatchClosure(myOriginalValue)
puts testerFunction.call("hello").to_s # prints true
My question is, is the following any better/worse/different? I've seen both approaches used in tutorials.
def createExactMatchClosure(str)
string_to_test = str
return lambda { |t|
return string_to_test == t
}
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于第一个版本工作得非常好,因此没有理由更喜欢第二个版本。
第一个版本和第二个版本之间的唯一区别在于,在第二个版本中,有两个变量被封闭,而不是只有一个(
str
和string_to_test
)。然而,您只能通过使用
binding
和eval
检查 lambda 的绑定来看到这一点,因此在实践中差异并不重要。Since the first version works perfectly fine, there is no reason to prefer the second.
The only difference between the first and the second version is that in the second version, there are two variables being closed over instead of just one (
str
andstring_to_test
).However you can only see that by inspecting the lambda's binding using
binding
andeval
, so in practice the difference does not matter.它不应该有什么不同。我不确定 Ruby 如何执行闭包的细节,但直觉上您不需要这样做。
闭包通常的工作方式是创建一个对象,该对象将保存对其范围之外声明的常量和变量的引用。在一种情况下它是局部变量,在另一种情况下它是参数。我认为无论哪种方式都应该无关紧要。
It shouldn't be any different. I am unsure about the particulars of how Ruby does closures but intuitively you should not need to do that.
The way a closure normally works is that an object is created that will hold a reference to constants and variables declared outside of its scope. In one case it's a local variable in the other case it's a parameter. I think it should not matter either way.