この記事の内容
Rubyにおけるクラス・メソッド・initializeの継承
この記事を書いた理由
忘れた時に確認するため
コード例
sample.rb
#親クラス
class Sample
attr_accessor :name,:price
def initialize(name,price)
@name = name
@price = price
end
def info()
return "#{@name} ¥#{@price}-"
end
end
sample1 = Sample.new("sample1",1000)
sample2 = Sample.new("sample2",2000)
sample3 = Sample.new("sample3",3000)
sample4 = Sample.new("sample4",4000)
samples = [sample1,sample2,sample3,sample4]
puts "-----------------"
samples.each do |sample|
puts sample.info()
puts "-----------------"
end
#子クラス
class Subsample < Sample
attr_accessor :memo
def initialize(name,price,memo)
super(name,price)
@memo = memo
end
def info()
super() + " #{@memo}"
end
end
subsample1 = Subsample.new("subsample1",5000,"memo1")
puts subsample1.info()
command
-----------------
sample1 ¥1000-
-----------------
sample2 ¥2000-
-----------------
sample3 ¥3000-
-----------------
sample4 ¥4000-
-----------------
subsample1 ¥5000- memo1