LoginSignup
1
0

More than 3 years have passed since last update.

【Ruby】インスタンスの生成について

Last updated at Posted at 2020-12-15

問題:クラスFruitsを以下の仕様で定義してください。

クラス変数
・sum

インスタンス変数
・name
・price

クラスメソッド
・get_sum
↪️"合計の価格は「クラス変数sum」円です"と表示

インスタンスメソッド
・initialize
↪️引数で名前、価格を渡し、インスタンス変数nameとpriceに代入する
 sumにpriceを足し合わせる

定義したら、クラスFruitsから以下の3つのインスタンスを生成しましょう

インスタンス

インスタンス名 名前 価格
apple リンゴ 120
orange オレンジ 200
strawberry イチゴ 60

雛形
作ってもらうプログラムのひな形は以下です。

class Fruits
    # ここにクラスの定義を書き加えてください
  end

  # 以下で3つのインスタンスを生成してください

  # 生成したらクラスメソッドget_sumを呼んで合計価格を表示しましょう

①まずクラスFruitsの定義し、クラス変数sumとクラスメソッドget_sumを定義。

②次にインスタンス変数nameとpriceをinitializeメソッドの中で定義。
initializeメソッドはnewメソッドの引数を受け取ることが可能。
名前と価格をnewメソッドから受け取ってインスタンス変数に代入する。
そしてinitializeメソッドで受け取った価格の引数priceをクラス変数「@@sum」に足し合わせる。

③newメソッドでインスタンス生成時に引数として名前と価格を渡す。

get_sumを呼び出して完了。

解答

 class Fruits
    @@sum = 0

    def self.get_sum
      puts "合計の価格は#{@@sum}円です"
    end

    def initialize(name, price)
      @name = name
      @price = price
      @@sum = @@sum + price
    end
  end

  apple = Fruits.new("リンゴ", 120)
  orange = Fruits.new("オレンジ", 200)
  strawberry = Fruits.new("イチゴ", 60)

  Fruits.get_sum

1
0
0

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
1
0