Why can I access private/protected methods using Object#send in Ruby?
- by smotchkkiss
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?