はこれを試してみてください。
class Device
singleton_class.send(:attr_accessor, :cost_per_kwh)
def initialize(name, watts)
@name = name
@watts = watts
end
def daily_cost(hours_per_day)
self.class.cost_per_kwh * kwh_per_day(hours_per_day)
end
def monthly_cost(hours_per_day)
30 * daily_cost(hours_per_day)
end
private
def kwh_per_day(hours_per_day)
hours_per_day * @watts/1000
end
end
singleton_class.send(:attr_accessor, :cost_per_kwh)
クラスインスタンス変数@cost_per_kwh
用セッターとゲッターを作成します。
まず、関心のあるすべてのデバイスのコスト計算に使用されるkwhあたりのコストを取得して保存します。
puts "Please enter the cost per kwh in $"
Device.cost_per_kwh = gets.chomp.to_f
と仮定
Device.cost_per_kwh = 0.0946
関心の各デバイスのコストを計算します。
puts "What is the name of the device?"
name = gets.chomp
puts "How many watts does it draw?"
watts = gets.chomp.to_f
我々は今、クラスのインスタンスを作成することが
name = "chair"
watts = 20000.0
と仮定する。
device = Device.new(name, watts)
#=> #<Device:0x007f9d530206f0 @name="chair", @watts=20000.0>
最後に、特定のデバイスのコストの将来の計算で変更される可能性のある唯一の変数です。
puts "How many hours do you use the #{name} daily?"
hours_per_day = gets.chomp.to_f
最後に、我々はコストを計算してもよい
hours_per_day = 0.018
を想定。
puts "Daily cost: $#{ device.daily_cost(hours_per_day)}"
Daily cost: $0.034056€
puts "Monthly_cost (30 days/month): $#{ 30 * device.daily_cost(hours_per_day) }"
Monthly_cost (30 days/month): $1.0216800000000001
と仮定状況は、デバイスが増加及び使用を変更します。 1日の更新時間のみが必要です。例えば、
puts "How many hours do you use the #{name} daily?"
hours_per_day = gets.chomp.to_f
は今
hours_per_day = 1.5
を仮定すると
puts "Daily cost: $#{ device.daily_cost(hours_per_day)}"
Daily cost: $2.838
puts "Monthly_cost (30 days/month): $#{ 30 * device.daily_cost(hours_per_day) }"
Monthly_cost (30 days/month): $85.14
1例えば新大統領の選挙。
なぜ '@@ kwh'はクラス変数ですか? –
私は 'montly_cost'は' monty_cost'とすべきだと考えています。それはMonty PythonのFlying Circusに関するものと仮定しています。 –