1.
3.
结论:
1.ruby的私有方法只能被隐式self调用,而public和protected 方法可以被显式self和隐式self调用,隐式self更具灵活性。
2.隐式self如果遇到没有的方法会按照类的类继承和mixin的优先级查找直到,而显式self不会。
class DiffSelf
public
def method1
puts "call method1"
end
def method2
puts "call method2"
self.method1
end
def method3
puts "call method3"
method1
end
end
t=DiffSelf.new
t.method2
#call method2
#call method1
t.method3
#call method3
#call method1
2.
class DiffSelf
private
def method1
puts "call method1"
end
public
def method2
puts "call method2"
self.method1
end
def method3
puts "call method3"
method1
end
end
t=DiffSelf.new
t.method2
#call method2
#private method error
t.method3
#call method3
#call method1
3.
class DiffSelf1
private
def puts(str)
"private method :#{str}"
end
public
def call_puts_with_self(str)
self.puts str
end
def call_puts_without_self(str)
puts str
end
end
t=DiffSelf.new
t.call_puts_without_self("Hello,world!") #Hello ,world!
t.call_puts_with_self("Hello,world!")#private method error
结论:
1.ruby的私有方法只能被隐式self调用,而public和protected 方法可以被显式self和隐式self调用,隐式self更具灵活性。
2.隐式self如果遇到没有的方法会按照类的类继承和mixin的优先级查找直到,而显式self不会。