试试这个。
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 创建一个setter 和getter。
首先,获取并保存每千瓦时的成本,该成本将用于计算所有感兴趣的设备的成本。
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例如选举新总统。