Why can I access private/protected methods using Object#send in Ruby?

Posted by smotchkkiss on Stack Overflow See other posts from Stack Overflow or by smotchkkiss
Published on 2010-03-25T20:30:29Z Indexed on 2010/03/25 20:33 UTC
Read the original article Hit count: 430

The 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 of 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

The question

The section labeled "Test Output" is the expected result. So why can I access private/protected method by simply Object#send?

Perhaps more important:

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

© Stack Overflow or respective owner

Related posts about ruby

Related posts about best-practices