Try this.
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) creates a setter and getter for the class instance variable @cost_per_kwh.
First, obtain and save the cost per kwh, which will be used in the calculation of cost for all devices of interest.
puts "Please enter the cost per kwh in $"
Device.cost_per_kwh = gets.chomp.to_f
Suppose
Device.cost_per_kwh = 0.0946
Calculate the costs for each device of interest.
puts "What is the name of the device?"
name = gets.chomp
puts "How many watts does it draw?"
watts = gets.chomp.to_f
Suppose
name = "chair"
watts = 20000.0
We may now create a class instance.
device = Device.new(name, watts)
#=> #<Device:0x007f9d530206f0 @name="chair", @watts=20000.0>
Lastly, obtain hours per days, the only variable likely to change in future calculations of costs for the given device.
puts "How many hours do you use the #{name} daily?"
hours_per_day = gets.chomp.to_f
Lastly, suppose
hours_per_day = 0.018
then we may compute the costs.
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
Suppose circumstances change1 and use of the device increases. We need only update hours per day. For example,
puts "How many hours do you use the #{name} daily?"
hours_per_day = gets.chomp.to_f
Suppose now
hours_per_day = 1.5
Then
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 The election of a new president, for example.
@@kwha class variable?montly_costshouldmonty_cost, assuming it concerns Monty Python's Flying Circus.