1

How can I create an aliased method that wraps a method that yields to a block that uses $1 variables?

More specifically, I want to monkeypatch String#sub (yes, I know that it is not a good practice) to modify the regexps passed to it before they are used.

I tried the following code without success.

class String
    alias :sub_orig :sub
    def sub(*args, &block)
        # do stuff with args
        sub_orig(*args, &block)
    end
end

The following test shows what the problem is

"mark = good".sub(/(good)|(bad)/) { "very " + $1 }
TypeError: can't convert nil into String
4

1 回答 1

1

这不是您问题的直接答案,但传递给 sub 的块接收匹配字符串作为参数,因此:

"mark = good".sub(/(good)|(bad)/) { |str| "very #{ str }" }
=> "mark = very good"

你能展示你想要做什么的更复杂的用法吗?

于 2013-02-16T17:06:12.947 回答