Reputation: 5239
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
Upvotes: 2
Views: 115
Reputation: 13655
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.
Upvotes: 1
Reputation: 370132
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
and string_to_test
).
However you can only see that by inspecting the lambda's binding using binding
and eval
, so in practice the difference does not matter.
Upvotes: 3