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

后端 未结 2 548
抹茶落季
抹茶落季 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.

提交回复
热议问题