Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

ruby - How do I make a class whose constructor looks like the constructor of a built-in class?

Complex is a built-in class. To make a Complex object, I write:

Complex(10, 5)

But if I create my own class Thing:

class Thing
  def initalize()
  end
end

to create a new Thing, I have to write:

Thing.new(...)

Is it possible to create a constructor for Thing so I can write:

Thing(...)

and have it act just like a built-in class such as Complex(1,1)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Complex can refer to either the Complex class, or to the Complex method defined in Kernel:

Object.const_get(:Complex) #=> Complex
Object.method(:Complex)    #=> #<Method: Class(Kernel)#Complex>

The latter is called a global method (or global function). Ruby defines these methods in Kernel as both, private instance methods:

Kernel.private_instance_methods.grep /^[A-Z]/
#=> [:Integer, :Float, :String, :Array, :Hash, :Rational, :Complex]

and singleton methods:

Kernel.singleton_methods.grep /^[A-Z]/
#=> [:Integer, :Float, :String, :Array, :Hash, :Rational, :Complex]

Just like any other method in Kernel:

These methods are called without a receiver and thus can be called in functional form

You can use module_function to add your own global method to Kernel:

class Thing
end

module Kernel
  module_function

  def Thing
    Thing.new
  end
end

Thing          #=> Thing                      <- Thing class
Thing()        #=> #<Thing:0x007f8af4a96ec0>  <- Kernel#Thing
Kernel.Thing() #=> #<Thing:0x007fc111238280>  <- Kernel::Thing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...