我理解
Ruby的
#initialize method is private.然而,让我感到困惑的是Ruby如何将该方法设为私有.
我们通常定义这样的类:
- class Cat
- def initialize(name)
- @name = name
- end
- def say_name
- puts @name
- end
- end
其中#initialize似乎与#say_name一起公开定义.在类定义之后,Ruby如何设置#initialize private?
解决方法
Yukihiro Matsumoto (the inventor of Ruby) has said:
#initialize is,by its design,supposed to be called only from within #new to separate per object/class initialization from the #new,thus you don’t have to redefine #new. When you need/want to redefine #new,it’s a sign of a bad design,I believe.
One of the reason #initialize being private is to tell you bad design.