gpt4 book ai didi

ruby - Ruby 如何使#initialize 私有(private)化?

转载 作者:数据小太阳 更新时间:2023-10-29 06:57:25 25 4
gpt4 key购买 nike

我理解 Ruby 的 #initialize method is private .然而,让我感到困惑的是 Ruby 是如何将方法设为私有(private)的。

我们通常这样定义类:

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.

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

关于ruby - Ruby 如何使#initialize 私有(private)化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29372714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com