LoginSignup
0
0

More than 1 year has passed since last update.

Ruby クラスとインスタンスを利用してプログラムを作成

Posted at

クラス・インスタンスを利用してプログラムを作成しよう

条件は以下の通りです。

  • Bookクラスを作成する
  • Bookクラスは@title@priceをプロパティとして持っている
  • attr_readerを使用する
  • Bookクラスのインスタンスを作成する(タイトル、価格は任意)
  • 作成したインスタンスから、タイトルと価格を取得し画面に表示させる。

attr_readerとは?

attr_readerメソッドとは、主に記述量を減らすために活用されます。
インスタンス変数を呼び出すメソッドを定義するメソッドです。
以下(例1)(例2)は結果は同じとなりますが、記述量に差があります。

(例1)

# attr_readerを使用しない場合
class Dog
  def initialize(name)
    @name = name
  end

  def name
    @name
  end

end

dog = Dog.new("ポチ")
puts dog.name

(例2)

# attr_readerを使用した場合
class Dog
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

dog = Dog.new("ポチ")
puts dog.name

それでは問題に移ります。

# 自分の回答
class Book
  attr_reader :title, :price

  def initialize(title, price)
    @title = title
    @price = price
  end
end

book = Book.new("プログラミングについて", 3000)
puts book.title
puts "#{book.price}円"

# 模範回答
class Book
  attr_reader :title, :price

  def initialize(title, price)
   @title = title
   @price = price
  end
end

book = Book.new("プロを目指す人のためのRuby入門", 3218)
puts book.title
puts "#{book.price}円"

解説

attr_reader :title, :price

上記コードを書くことで、@title@priceにアクセスすることができます。
ちなみに、attr_readerを使わない場合の回答は以下のようになります。

# attr_readerを使わない場合
class Book

  def initialize(title, price)
   @title = title
   @price = price
  end

  def title
    @title
  end

  def price
    @price
  end

end

book = Book.new("プロを目指す人のためのRuby入門", 3218)
puts book.title
puts "#{book.price}円"
0
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
0
0