`initialize':未定义的方法`gauge'(NoMethodError)

时间:2010-09-10 18:49:47

标签: ruby

有谁知道我为什么会收到这个错误:initialize': undefined method测量'#(NoMethodError)?!我的意思是我使用attr_accessor作为测量仪的吸气剂和定位器,但它仍然说我没有声明它。我在下面发布了一段代码。提前谢谢。

class ParkingLotGuest < Guest

attr_accessor :gauge, :electricity_bill, :type_of_stay  

def initialize (name, address, phone, arrival, lives_where, type_of_stay, guest_wishes_electricity)
    super(name, address, phone, arrival, lives_where)
    @type_of_stay = type_of_stay
    @electricity_bill = 0 
    @gauge = 0;
    if (guest_wishes_electricity[0,1] == "j")
        @gauge = lives_where.gauge
    end
end

以下是parking_lot类的代码:

class Parking_Lot

attr_accessor :nr
    attr_accessor :gauge
attr_reader :electricity_meter

# Initiates a new caravan plot with the number nr and a electricity meter between
# 2000 och 4000.
def initialize (nr)
    @nr = nr
            @gauge = gauge
    @electricity_meter = 4000-rand(2000)
end

# increases the electricity meter for use with a random amount between 
# 10-80 kWh per 24 h.
def increase_meter(days)
    generatedUse = (10+rand(70))*days
    puts "Increases the meter with " + generatedUse.to_s + " kWh."
    @electricity_meter += generatedUse
end

# Returns a string representation of the camping plot.
def to_s

  "Plot #{@nr+1} Electricity meter: #{@electricity_meter} kWh"

end 
end

野营班的代码。

@staticGuests = Array[   
    ParkingLotGuest.new("Logan Howlett", "Tokyo", "07484822", 1, @parking_lots[0], "Husvagn", "j", @gauge), 
    ParkingLotGuest.new("Scott Summers",    "Chicago", "8908332", 2, @parking_lots[1], "Husbil", "j", @gauge),
  ParkingLotGuest.new("Hank Moody",     "Boston", "908490590",23, @parking_lots[2], "Tält", "n", @gauge),
  CabinGuest.new("Jean Grey", "Detroit", "48058221", 4, @parking_lots[3]['Wolverine']),
  CabinGuest.new("Charles Xavier",  "Washington DC", "019204822", 5, @parking_lots[4]['Thanos'])
]                                                                                                                      

1 个答案:

答案 0 :(得分:1)

更仔细地看一下错误:

undefined method `gauge' for #<Parking_Lot:0x10017c860 @electricity_meter=3622, @nr=0> (NoMethodError) 

这说的是Parking_Lot的一个实例接收了一个名为gauge的方法的方法调用,但它没有gauge方法。

在这一行中,只有一个方法调用。

@gauge = lives_where.gauge

@gauge = ...直接分配给实例变量@gauge,绕过了setter方法,所以不是这样。

lives_where.gauge可能就是在抱怨。 lives_whereParking_Lot吗?