class Main
def say_hello
puts "Hello"
end
private
def say_hi
puts "hi"
end
end
class SubMain < Main
def say_hello
puts "Testing #{say_hi}"
end
end
test = SubMain.new
test.say_hello()
输出:
嗨
测试
答案 0 :(得分:11)
不同之处在于,在ruby中,您可以隐式但不显式地调用子类中的私有方法。受保护可以双向调用。至于为什么?我想你不得不问马茨。
示例:
class TestMain
protected
def say_bueno
puts "bueno"
end
def say_ni_hao
puts "ni hao"
end
private
def say_hi
puts "hi"
end
def say_bonjour
puts "bonjour"
end
end
class SubMain < TestMain
def say_hellos
# works - protected/implicit
say_bonjour
# works - protected/explicit
self.say_ni_hao
# works - private/implicit
say_hi
# fails - private/explicit
self.say_bonjour
end
end
test = SubMain.new
test.say_hellos()