8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Ruby]クラス・メソッド・initializeの継承

Last updated at Posted at 2018-07-08

この記事の内容

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
8
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?