undefined local variable or method (filling an array)

T

Thufir

I've been working on this for quite some time and don't understand the
error:


C:\code>
C:\code>type monsters.rb
require 'Dragon'
require 'ArrayOfCreaturesAttributes'
require 'CreatureAttributes'

monsters[0]=ArrayOfCreaturesAttributes.instance

C:\code>
C:\code>type ArrayOfCreaturesAttributes.rb
require 'singleton'
require 'Creature'
require 'CreatureAttributes'

class ArrayOfCreatureAttributes < Array

include Singleton


end
C:\code>
C:\code>type Creature.rb
require 'CreatureAttributes'

class Creature

Creature.extend CreatureAttributes
include CreatureAttributes


end
C:\code>


C:\code>
C:\code>monsters.rb
C:/code/monsters.rb:6: undefined local variable or method `monsters'
for main:Ob
ject (NameError)

C:\code>
 
T

Thufir

Thufir said:
I've been working on this for quite some time and don't understand the
error:
C:/code/monsters.rb:6: undefined local variable or method `monsters'
for main:Ob
ject (NameError)

my_program.rb:

monsters[0] = 10

--output:--
undefined local variable or method `monsters' for main:Object
(NameError)

Normally, variables spring into existence when you assign to them.
However, the statement above works a little differently. The characters
'[]=' are actually the name of a method in the Array class. That means
the the code above is using the variable monsters to call that method.
However, in order to call a method of the Array class, you need an
existing array instance. But, nowhere in the code is an array
previously assign to the variable monsters.

Try this instead:

my_program.rb:

monsters = []
monsters[0] = 10


Gee, it was so weird and frustrating. Thank you all!



-Thufir
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top