Ruby如何将#initialize私有化?

前端之家收集整理的这篇文章主要介绍了Ruby如何将#initialize私有化?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我理解 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.

总而言之,它是Ruby的内置功能,#inititize是自动私有的,因此开发人员不会轻易地在.new类方法之外调用它.

原文链接:https://www.f2er.com/ruby/269276.html

猜你在找的Ruby相关文章