都是单例方法public吗?
Are all singleton methods public?
单例方法一定是public吗?如果不是,private/protected 单例方法什么时候有用?
单例方法不一定是public。 Private/protected 单例方法在与常规 private/protected 方法相同的情况下很有用 - 例如,作为您不打算在 class.
之外调用的辅助方法
class Foo
end
f = Foo.new
class << f
def foo
helper
# other stuff
end
private
def helper
end
end
如果需要,您可以将单例方法设为私有:
class Foo
end
f = Foo.new
def f.bar
"baz"
end
f.singleton_class.send :private, :bar
f.bar # => NoMethodError: private method `bar' called for #<Foo:0x007f8674152a00>
f.send :bar # => "baz"
这是否真的有用取决于你在做什么。
如果需要,您可以将单例方法设为私有:
class Foo
def self.bar
# ...
end
private_class_method :bar
end
它们有用吗?嗯。对于 Ruby 2.2
ObjectSpace.each_object(Module).flat_map { |m|
m.singleton_class.private_methods(false) }.size
#=> 900
大部分是类单例的私有方法类:
ObjectSpace.each_object(Class).flat_map { |c|
c.singleton_class.private_methods(false) }.size
#=> 838
[编辑:以下是我对原文post的编辑,以提供更多有用的信息。)
有一件事让我很困惑。让:
a = ObjectSpace.each_object(Class).map { |c|
[c, c.singleton_class.private_methods(false)] }.to_h
b = ObjectSpace.each_object(Class).map { |c|
[c, c.private_methods(false)] }.to_h
def diff(a,b)
a.map {|k,v| b.key?(k) ? [k,v-b[k]] : [k,v] }.reject { |_,a| a.empty?}.to_h
end
我预计 diff(a,b) == diff(b,a) == {}
。让我们看看:
diff(a,b)
#=> {}
diff(b,a)
#=> {Gem::Specification=>[:skip_during, :deprecate],
# Complex=>[:convert],
# Rational=>[:convert],
# Random=>[:state, :left],
# Time=>[:_load]}
嗯嗯。
单例方法一定是public吗?如果不是,private/protected 单例方法什么时候有用?
单例方法不一定是public。 Private/protected 单例方法在与常规 private/protected 方法相同的情况下很有用 - 例如,作为您不打算在 class.
之外调用的辅助方法class Foo
end
f = Foo.new
class << f
def foo
helper
# other stuff
end
private
def helper
end
end
如果需要,您可以将单例方法设为私有:
class Foo
end
f = Foo.new
def f.bar
"baz"
end
f.singleton_class.send :private, :bar
f.bar # => NoMethodError: private method `bar' called for #<Foo:0x007f8674152a00>
f.send :bar # => "baz"
这是否真的有用取决于你在做什么。
如果需要,您可以将单例方法设为私有:
class Foo
def self.bar
# ...
end
private_class_method :bar
end
它们有用吗?嗯。对于 Ruby 2.2
ObjectSpace.each_object(Module).flat_map { |m|
m.singleton_class.private_methods(false) }.size
#=> 900
大部分是类单例的私有方法类:
ObjectSpace.each_object(Class).flat_map { |c|
c.singleton_class.private_methods(false) }.size
#=> 838
[编辑:以下是我对原文post的编辑,以提供更多有用的信息。)
有一件事让我很困惑。让:
a = ObjectSpace.each_object(Class).map { |c|
[c, c.singleton_class.private_methods(false)] }.to_h
b = ObjectSpace.each_object(Class).map { |c|
[c, c.private_methods(false)] }.to_h
def diff(a,b)
a.map {|k,v| b.key?(k) ? [k,v-b[k]] : [k,v] }.reject { |_,a| a.empty?}.to_h
end
我预计 diff(a,b) == diff(b,a) == {}
。让我们看看:
diff(a,b)
#=> {}
diff(b,a)
#=> {Gem::Specification=>[:skip_during, :deprecate],
# Complex=>[:convert],
# Rational=>[:convert],
# Random=>[:state, :left],
# Time=>[:_load]}
嗯嗯。