Ruby类被称为方法

eir*_*kir 3 ruby

有没有办法定义一个类,以便您可以将该类作为执行所需代码的方法调用?例如(不起作用):

class MySpecialClass
  def self(x)
    x*x
  end
end
Run Code Online (Sandbox Code Playgroud)

在控制台中:

MySpecialClass(4)
=> 16
MySpecialClass(5)
=> 25
Run Code Online (Sandbox Code Playgroud)

我似乎无法在网上找到任何东西,但是一些Ruby(2.1.2)类似乎能够有类似的行为,例如String:

String("hello")
=> "hello"
String(3)
=> "3"
Run Code Online (Sandbox Code Playgroud)

请注意,这与String#new类方法的行为不同:

String.new(3)
TypeError: no implicit conversion of Fixnum into String

Aug*_*ust 9

您所要做的就是定义一个与该类同名的方法:

def MySpecialClass(x)
  x * x
end
Run Code Online (Sandbox Code Playgroud)

String(foo)实际上是调用Kernel#String方法.