Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby - Method call to object in array
    primarykey
    data
    text
    <p>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.</p> <p>I have an array of camping lots, each containing a guest. I initialize the lots like this: </p> <pre><code>lots = Array.new for i in (1..36) lots[i] = Lot.new(i) end </code></pre> <p>Further down I create a <code>Guest</code> object, initialize it, and now I want to add the <code>Guest</code> to my <code>Lot</code>. The method in the class <code>Lot</code> looks like this:</p> <pre><code>def AddGuest(guest) @guest = guest end </code></pre> <p>The problem comes when I want to call the method, as the <code>Lot</code> is in an <code>Array</code>.</p> <pre><code>lots[lotnumber].AddGuest(guest) </code></pre> <p>This call gives me the error:</p> <pre><code>undefined method `+@' for #&lt;Guest:0x2c1ff14&gt; (NoMethodError) </code></pre> <p>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 <code>AddGuest</code> method in the <code>Array</code> class? I'm used to doing things like this in C++.</p> <p>Below is the full source (the relevant parts at least).</p> <p>Entire <code>Lot</code> class:</p> <pre><code>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 </code></pre> <p>Parts of main.rb</p> <pre><code>#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 </code></pre> <p>Player input omitted</p> <pre><code>#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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload