LoginSignup
0
0

More than 1 year has passed since last update.

クラス外からインスタンス変数を呼び出す際に簡単に使えるメソッド

Posted at

Rubyのクラスメソッドに属性としてinitializeメソッドで定義したインスタンス変数の値を外部から呼び出す際に利用できるattr_readerメソッドの使い方について記述していきます。

例として各支店の店舗名と売上の入力している値を外部から呼び出し、売上の合計をクラスメソッドで呼び出し、出力する場合

メソッドで定義して呼び出す場合

class Shop
  @@total_sales = 0

  def self.salesAll
    @@total_sales
  end

  def initialize(shop_name,sales)
    @shop_name = shop_name
    @sales = sales
    @@total_sales += @sales
  end

  def shopName
    @shop_name
  end

  def sales
    @sales 
  end
end

shop1 = Shop.new("東京", 500000)
shop2 = Shop.new("大阪", 400000)
puts "#{shop1.shopName}の売上は#{shop1.sales}円で、#{shop2.shopName}の売上は#{shop2.sales}円です"
puts "全体の売上は#{Shop.salesAll}円です。"

インスタンス変数に入力した値はスコープによりクラス外から呼び出せないため、その値を呼び出すときにはインスタンスメソッドにて変数を呼び出すことで値を外部からでも取得できるが、個別に呼び出す際にはメソッドの記述が多くなってしまう。

そこで記述量を減らして同じことができるように
attr_readerというメソッドを使うと

class Shop
  @@total_sales = 0
  attr_reader :shop_name, :sales

  def self.salesAll
    @@total_sales
  end

  def initialize(shop_name,sales)
    @shop_name = shop_name
    @sales = sales
    @@total_sales += @sales
  end
end

shop1 = Shop.new("東京", 500000)
shop2 = Shop.new("大阪", 400000)
puts "#{shop1.shop_name}の売上は#{shop1.sales}円で、#{shop2.shop_name}の売上は#{shop2.sales}円です"
puts "全体の売上は#{Shop.salesAll}円です。"

attr_readerの後ろに:インスタンス変数名と記述すると
外部からインスタンス名.インスタンス変数の形で呼び出すことで
インスタンス変数情報を取得できる

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