Alle venerdì 29 giugno 2007, Alin Popa ha scritto:
Hi there,
I have a little problem regarding private methods in Ruby.
I have the following case:
class MyClass
private
def my_method
puts "something from my method"
end
end
myClass = MyClass.new
begin
myClass.my_method
rescue
puts "Method cannot be called because is private"
end
myClass.send("my_method")
So, can anyone help me by explaining in a logical way, what is the point
of private methods in ruby since I can call it using "send" ?
Thanks in advance,
Alin
In general, the idea behind private methods is that they can't be called from
outside the object they belong to. In ruby, this is achieved by allowing
calling them only without an explicit receiver. This means that the you can
call them when the receiver of the method is the implicit receiver (self),
that is, only from within instance methods:
class MyClass
def private_method
puts "This is private_method"
end
private :private_method
def test_method
puts "This test method is abouto to call private_method"
private_method
end
end
obj = MyClass.new
obj.test_method
puts "---"
obj.private_method
The output is:
This test method is abouto to call private_method
This is a private method
···
---
./script.rb:20: private method `private_method' called for
#<MyClass:0xb7c171d8> (NoMethodError)
Note that no receiver is allowed for private method, not even self. So,
test_method couldn't have been written as:
def test_method
puts "This test method is abouto to call private_method"
self.private_method
end
Doing this would again result in a NoMethodError exception.
I hope this helps
Stefano