一个小技巧,在Ola Bini 的blog上看到的。
假设你想要这样一个类:
创建这个类的时候send一个block给它,然后在后面可以通过某个方法名来调用这个block。
假设你想要这样一个类:
创建这个类的时候send一个block给它,然后在后面可以通过某个方法名来调用这个block。
class DoSomething
def initialize
(class << self; self; end).send :define_method, :call do
yield
end
end
end
d = DoSomething.new do puts "hello world"
end
d.call
d.call