code in file abc.rb
class SuperABC
def initialize
@a = 1
@b = 2
@c = 3
end
end
class ABC < SuperABC
def initialize
super # keyword
@a = 0
end
def a
puts @a
end
def b
puts @b
end
def c
puts @c
end
end
t = ABC.new
t.a
t.b
t.c
ruby abc.rb
PS C:\Users\Administrator\RubyCode> ruby abc.rb
0
2
3
why?
关键词 super
保留了SuperABC
类中的初始值,而后在ABC
类里面,只对变量@a
进行了重新赋值为零,所以最终输出是 0 2 3
reference
《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
4.2.5. Going up the method search path with super
Zzz・・・・・・
/ヽ、
/__ヾ--、
~(=-ω-)ノ )~
---------------
http://emoji.vis.ne.jp/neruyo_3koma2.htm