请问我"为什么要这样做?"我只是在探索Ruby的角落和缝隙,没有具体的目标.
有些Ruby类可以用括号实例化,而不是显式调用#new
方法. 例如,
irb> require 'pathname'
irb> p=Pathname('/etc/xdg/autostart')
=> #<Pathname:/etc/xdg/autostart>
irb> n=Pathname.new('/etc/xdg/autostart')
=> #<Pathname:/etc/xdg/autostart>
irb> p==n
=> true
有些人用这个来做施法/胁迫,比如Integer(4.5)
. 可能还有其他的用途我还没有遇到,或者记不清了.
然而,我还没有找到一种方法来实现自定义类:
irb> class Foo ; def initialize(*args) ; @args=args ; end ; end
=> :initialize
irb> f1=Foo.new(1,2,3)
=> #<Foo:0x00007f330a29f4e8 @args=[1, 2, 3]>
irb> fp=Foo(1,2,3)
(irb):7:in `<main>': undefined method `Foo' for main:Object (NoMethodError)
Did you mean? for
我唯一能弄清楚的是,Pathname
和Integer
(例如)都使用C代码,并且不知何故是内核方法:
irb> Object.method(:Pathname)
=> #<Method: #<Class:Object>(Kernel)#Pathname(_)>
irb> Object.method(:Integer)
=> #<Method: #<Class:Object>(Kernel)#Integer(*)>
irb> Object.method(:Foo)
(irb):10:in `method': undefined method `Foo' for class `#<Class:Object>' (NameError)
Did you mean? for
所以这似乎是C/.so
扩展代码提供的.
然而,是否可以简单地使用原生Ruby代码而不诉诸于类似以下的笨拙?
irb> Object.define_method(:Foo) { |*args| Foo.new(*args) }
=> :Foo
irb> Foo(1,2,3)
=> #<Foo:0x00007f330a3b9018 @args=[1, 2, 3]>