我在gsub!
的替换参数内使用lambda。当以不同的方法定义lambda时,Regexp.last_match
或$~
为空,违背了lambda在调用时评估表达式的预期行为。如果我运行这个代码,我会得到一个错误,但是如果我在转录的第一行取消注释,它就会起作用。当在另一种方法中定义lambda时,`lambda中的Regexp.last_match`调用为`nil`
class Test
def initialize
@@replace = lambda { "#{callback('*', Regexp.last_match)}" }
end
def transcribe(s)
#@@replace = lambda { "#{callback('*', Regexp.last_match)}" }
s.gsub!(/(?<l>.?)[aeiou](?<r>.?)/) do
$~[:l] + (@@replace).call + $~[:r]
end
s
end
def callback(replace, match)
raise "Error: Match is empty" if match.nil?
return replace.upcase
end
end
t = Test.new
puts t.transcribe('example')
有人可以告诉我,如果我做错了什么,或者它是一个错误?
我用Google搜索了它:ruby Regexp.last_match lambda,并且在不同的情况下,似乎有一个$1
的错误,但我不明白它是否与此相关。