Are all single-user mode methods publicly available?

Is singleton required by the public? If not, when will the private / protected singleton method be useful?

+4
source share
4 answers

Singleton methods do not have to be publicly available. Private / protected single-user methods are useful in the same situations as regular private / protected methods - for example, as a helper method that you are not going to call outside the class.

class Foo
end

f = Foo.new

class << f
  def foo
    helper
    # other stuff
  end

  private
  def helper
  end
end
+5
source

You can make the singleton method private if you want:

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"

whether this is really useful depends on what you do.

+1
source

singleton- , :

class Foo

  def self.bar
    # ...
  end
  private_class_method :bar

end
+1

? . Ruby 2.2

ObjectSpace.each_object(Module).flat_map { |m|
  m.singleton_class.private_methods(false) }.size
  #=> 900

- singleton :

ObjectSpace.each_object(Class).flat_map { |c|
  c.singleton_class.private_methods(false) }.size
  #=> 838

[Edit: next edit my original post to provide more useful information.)

One thing puzzles me. Let be:

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

I was expecting diff(a,b) == diff(b,a) == {}. Let's get a look:

diff(a,b)
  #=> {} 

diff(b,a)
  #=> {Gem::Specification=>[:skip_during, :deprecate],
  #    Complex=>[:convert],
  #    Rational=>[:convert],
  #    Random=>[:state, :left],
  #    Time=>[:_load]} 

Hmmm.

0
source

All Articles