如何避免在Ruby中使用类变量

joh*_*ck1 0 ruby class-variables

我有一段使用类变量的代码.我已经读过Ruby中通常应该避免使用类变量.

类变量是@@cost@@kwh.

如何在不使用类变量的情况下重写以下内容?

class Device
 attr_accessor :name, :watt

 @@cost = 0.0946

 def initialize(name, watt)
   @name = name
   @watt = watt
 end

  def watt_to_kwh(hours)
    @@kwh = (watt / 1000) * hours
  end

  def cost_of_energy
    puts "How many hours do you use the #{self.name} daily?"
  hours = gets.chomp.to_i
    self.watt_to_kwh(hours)
    daily_cost = @@kwh * @@cost
    montly_cost = daily_cost * 30
    puts "Dayly cost: #{daily_cost}€"
    puts "montly_cost: #{montly_cost}€"
  end
end
Run Code Online (Sandbox Code Playgroud)

Ger*_*rry 5

@@cost表现得更像一个常量(即它在运行时不会改变),所以你应该使用一个:

COST = 0.0946
Run Code Online (Sandbox Code Playgroud)

@@kwh应该是一个实例变量,因为它仅在实例化对象中使用,因此您可以使用@kwh:

@kwh = (watt / 1000) * hours
Run Code Online (Sandbox Code Playgroud)

daily_cost = @@kwh * @@cost将变为:

daily_cost = @kwh * COST
Run Code Online (Sandbox Code Playgroud)

这将避免使用类变量,但您也可以@kwh完全消除,因为您不在其他任何地方使用它.

所以,而不是:

def watt_to_kwh(hours)
  @kwh = (watt / 1000) * hours
end
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

def watt_to_kwh(hours)
  (watt / 1000) * hours
end
Run Code Online (Sandbox Code Playgroud)

并在cost_of_energy方法中使用它:

def cost_of_energy
  puts "How many hours do you use the #{self.name} daily?"
  hours = gets.chomp.to_i
  daily_cost = watt_to_kwh(hours) * COST
  montly_cost = daily_cost * 30
  puts "Dayly cost: #{daily_cost}€"
  puts "montly_cost: #{montly_cost}€"
end
Run Code Online (Sandbox Code Playgroud)