Ruby – Method call to object in array

arraysruby

I'm working with a Ruby project for school, and have sadly not been able to find an answer to this question in my literature.

I have an array of camping lots, each containing a guest. I initialize the lots like this:

lots = Array.new

for i in (1..36)
  lots[i] = Lot.new(i)
end

Further down I create a Guest object, initialize it, and now I want to add the Guest to my Lot. The method in the class Lot looks like this:

def AddGuest(guest)
  @guest = guest
end

The problem comes when I want to call the method, as the Lot is in an Array.

lots[lotnumber].AddGuest(guest)

This call gives me the error:

undefined method `+@' for #<Guest:0x2c1ff14> (NoMethodError)

I have used require, so the classes know about each other. I've had quite a hard time understanding Ruby, could my error be that I try to access the AddGuest method in the Array class? I'm used to doing things like this in C++.

Below is the full source (the relevant parts at least).

Entire Lot class:

class Lot

  def initialize(number)
    @gauge = rand(2000) + 2000
    @number = number
    @guest = false
  end

  def Occupied()
    return @guest
  end

  def AddGuest(guest)
    @guest = guest
  end

  def RemoveGuest()
    @guest = false
  end

end

Parts of main.rb

#includes
require 'guest'
require 'lot'

#initiate comparison variables
userInput = "0"
numberOfGuests = 0
foundLot = false
guests = Array.new
lots = Array.new

#initialize lot list
for i in (1..36)
  lots[i] = Lot.new(i)
end

Player input omitted

#make sure lot is not taken
while foundLot == false do
  lotnumber = rand(35)+1
  if lots[lotnumber].Occupied() == false then
    foundLot = "true"
  end
end
foundLot = false

guest = Guest.new(firstName, lastName, adress, phone, arrival, lotnumber)
guests.insert(numberOfGuests, guest)
numberOfGuests++

lots[lotnumber].AddGuest(guest) #this is where error hits

end

end

end

Best Solution

The error appears to be related to your use of the ++ operator, which is, quite naturally, supported in C++, but is not supported in Ruby.

The equivalent is:

numberOfGuests += 1