Is initialize method (constructor) private or public in ruby?
在ruby中初始化方法(构造函数)是私有的还是公共的?
2 个解决方案
#1
16
Let's see:
让我们来看看:
class Test
def initialize; end
end
p Test.new.private_methods.sort.include?(:initialize)
This prints true
, so initialize
is a private method. This makes sense, it is only called by the new
class method if the object is created. If we want, we can do something like this:
这打印为true,因此initialize是一个私有方法。这是有道理的,只有在创建对象时才会被新类方法调用。如果我们想要,我们可以这样做:
class Test
def initialize
@counter = 0
end
def reset!
initialize
end
end
Misusing the constructor like this could however lead to problems if it does more than simple variable initialization.
如果它不仅仅是简单的变量初始化,那么滥用这样的构造函数可能会导致问题。
#2
4
The initialize
method in a class automatically becomes Private.
类中的initialize方法自动变为Private。
You can check it using:
您可以使用以下方式检查:
puts ClassName.private_methods.sort
#1
16
Let's see:
让我们来看看:
class Test
def initialize; end
end
p Test.new.private_methods.sort.include?(:initialize)
This prints true
, so initialize
is a private method. This makes sense, it is only called by the new
class method if the object is created. If we want, we can do something like this:
这打印为true,因此initialize是一个私有方法。这是有道理的,只有在创建对象时才会被新类方法调用。如果我们想要,我们可以这样做:
class Test
def initialize
@counter = 0
end
def reset!
initialize
end
end
Misusing the constructor like this could however lead to problems if it does more than simple variable initialization.
如果它不仅仅是简单的变量初始化,那么滥用这样的构造函数可能会导致问题。
#2
4
The initialize
method in a class automatically becomes Private.
类中的initialize方法自动变为Private。
You can check it using:
您可以使用以下方式检查:
puts ClassName.private_methods.sort