How do I get access to an outer variable in a closure in ruby?
I have the following dynamically created class th开发者_StackOverflow社区at is passed into the xpath function of nokogiri:
country = nil
ret = parent.xpath(".//text()[regex(.)]", Class.new{
def regex(node_set, lead)
result = node_set.find_all do |node|
node.text =~ POST_CODE_EXPRESSION || node.text =~ ZIP_CODE_EXPRESSION
end
result
end
}.new)
I would like to somehow access or set the country variable or get access to the outer self from within the regex function.
Is there anyway I can pass the outer self into the Class.new expression or can anyone suggest a better way?
Methods cannot be closures in Ruby, only blocks can:
country = nil
ret = parent.xpath(".//text()[regex(.)]", Class.new{
define_method(:regex) do |node_set, lead|
result = node_set.find_all do |node|
node.text =~ POST_CODE_EXPRESSION || node.text =~ ZIP_CODE_EXPRESSION
end
result
end
}.new)
By the way: your regex
method is much more complicated than it needs to be. It's simply equivalent to
define_method(:regex) do |node_set, lead|
node_set.find_all do |node|
node.text =~ POST_CODE_EXPRESSION || node.text =~ ZIP_CODE_EXPRESSION
end
end
You can do it like this:
x = 1
Class.new do
def initialize(binding)
eval 'x += 1', binding
end
end.new binding
p x # will print 2
It doesn't look very nice with eval but it works=)
精彩评论