我在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
的錯誤,但我不明白它是否與此相關。