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

独自空忆成欢 提交于 2019-12-01 17:15:09

问题


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

Rational(a,b)

(Notice the absence of the .new()portion compared to the normal Ruby syntax). What does this mean, precisely, compared to the normal new syntax? More importantly, how do I implement something like this in my own code, and why would I implement something like this? Specifically for the Rational class, why is this syntax used instead of the normal instantiation? And why is the new method private in the rational class? (And how/why would I do this in my own ruby code?) Thanks in advance for your answers, especially since I've asked so many questions.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4034174/ruby-syntax-question-rationala-b-and-rational-newa-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!