我想扩展 Proc 类,以便它的构造函数也可以采用参数散列,并将转换为具有某些元编程构造的方法。效果如下:
p = Proc.new(this: 100, that: 200, yes: 1, no: 2) { |arg| arg.even? }
p.call(1) # => false
p.this # => 100
p.yes # => 1
我想知道用 ruby 的方式做这样的事情。
最佳答案
class Proc
def initialize h; @h = h end
def method_missing k; @h[k] end
def respond_to_missing?; true end
end
p = Proc.new(this: 100, that: 200, yes: 1, no: 2) { |arg| arg.even? }
p.call(1) # => false
p.this # => 100
p.yes # => 1
关于ruby - Ruby 中的猴子修补和重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13769620/