Ruby syntax question: Rational(a, b) and Rational.new!(a, b)

后端 未结 2 545
抹茶落季
抹茶落季 2021-01-18 07:48

Today I came across the strange ruby syntax in the Rational class:

Rational(a,b)

(Notice the absence of the .new()portion comp

相关标签:
2条回答
  • 2021-01-18 08:27

    The method Rational() is actually an instance method defined outside of the class Rational. It therefore becomes an instance method of whatever object loads the library 'rational' (normally main:Object) in the same way that 'puts' does, for example.

    By convention this method is normally a constructor for the class of the same name.

    0 讨论(0)
  • 2021-01-18 08:32

    All you have to do is declare a global function with the same name as your class. And that is what rational.rb does:

    def Rational(a, b = 1)
      if a.kind_of?(Rational) && b == 1
        a
      else
        Rational.reduce(a, b)
      end
    end
    

    to make the constructor private:

    private :initialize
    

    and similarly for the new method:

    private_class_method :new
    

    I suppose Rational.new could be kept public and made to do what Rational() does, but having a method that turns its arguments into instances is consistent with Array(), String(), etc. It's a familiar pattern that's easy to implement and understand.

    0 讨论(0)
提交回复
热议问题