Undefined local variable or method (filling an array)

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>

Thufir wrote:

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

7stud – wrote:

The characters
‘[]=’ are actually the name of a method in the Array class.

To see that, you can also call the method ‘[]=’ using the normal
variable.method_name syntax:

monsters = []
monsters.[]=(0, 10) #’[]=’ is the name of a method

puts monsters[0]
—>10

7stud – wrote:

Try this instead:
monsters = []
monsters[0] = 10

Or this:
monsters = [10]

On Nov 9, 4:43 pm, 7stud – [email protected] wrote:

monsters[0] = 10
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

Posted viahttp://www.ruby-forum.com/.

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

-Thufir