クラス変数
【開発環境】
OS:Win11(64ビット)
Ruby 3.1.2
■クラス変数
クラス変数→クラスと、そのインスタンス全て使用できる変数で、@@変数名のように書く
「クラス変数.rb」ファイルを書く
#消費税額を計算するクラス
class TaxCalc
#クラス変数を宣言
@@tax_rate = 0.08
#インスタンス変数を初期化
def initialize(price)
@price = price
end
#消費税計算の実処理
def execute
@price * @@tax_rate
end
end
#executeメソッドを実行
calculator = TaxCalc.new(100)
p calculator.execute
・コマンドで実行する
Microsoft Windows [Version 10.0.22000.795]
(c) Microsoft Corporation. All rights reserved.
C:\Users\Owner>ruby D:\pg\Ruby31-x64\サンプルプログラム\クラス変数.rb
8.0
C:\Users\Owner>