Why can I access private / protected methods by sending a # object to Ruby?

Class

class A

  private
  def foo
    puts :foo
  end

  public
  def bar
    puts :bar
  end

  private
  def zim
    puts :zim
  end

  protected
  def dib
    puts :dib
  end
end

instance A

a = A.new

test

a.foo rescue puts :fail
a.bar rescue puts :fail
a.zim rescue puts :fail
a.dib rescue puts :fail
a.gaz rescue puts :fail

test output

fail
bar
fail
fail
fail

.send test

[:foo, :bar, :zim, :dib, :gaz].each { |m| a.send(m) rescue puts :fail }

.send output

foo
bar
zim
dib
fail

Question

The heading "Test Output" refers to the expected result. So why can I access the private / protected method simply Object#send?

Perhaps more important:

What is the difference between public/ private/ protectedin Ruby? When to use each? Can someone provide real world examples for use privateand protected?

+5
source share
1 answer

: send , . ( .)

: Ruby - . , . send , , private. Ruby 1.9 : private -respecting send send!, , , .

, private, protected public :

  • public
  • protected
  • private ( , setter, )
+8

All Articles