加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby如何将#initialize私有化?

发布时间:2020-12-17 04:32:11 所属栏目:百科 来源:网络整理
导读:我理解 Ruby的 #initialize method is private.然而,让我感到困惑的是Ruby如何将该方法设为私有. 我们通常定义这样的类: class Cat def initialize(name) @name = name end def say_name puts @name endend 其中#initialize似乎与#say_name一起公开定义.在
我理解 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类方法之外调用它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读