Simple program with a simple(?) error -- what's wrong?

R

RichardOnRails

Hi,

I put together to exercise simple Ruby constructs. It's posted at
http://www.pastie.org/237288.

Before I introduced the "indx" variable it worked fine. The statement
incrementing indx in the def causes the error:
undefined method `+' for nil:NilClass (NoMethodError)

I'm running:
ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]

Why doesn't the def use the instance of indx defined before the def?

Thanks in Advance,
Richard
 
R

reuben doetsch

[Note: parts of this message were removed to make it a legal post.]

The scope of indx is wrong, when you call it outside the function, it is
only accesible witin that scope, the outer scope and so you have you do this

def foo
indx=0
....
end

that will then work, you only need to call foo someplace if you want foo to
run. You only define it, creating the function does not call it.

On Sat, Jul 19, 2008 at 10:39 PM, RichardOnRails <
 
S

Siep Korteling

reuben said:
The scope of indx is wrong, when you call it outside the function, it is
only accesible witin that scope, the outer scope and so you have you do
this

def foo
indx=0
....
end
(...)
Or replace "indx" with "@indx".
Regards,
Siep
 
R

RichardOnRails

(...)
Or replace "indx" with "@indx".
Regards,
Siep

Thanks Reuben and Siep for you responses.

The following worked perfectly for creating sequentially numbered
lines: as "def" was invoked successively with various arguments:

@indx=0
def disp(s)
@index += 1
printf( [snip]

However, "index=0" inside the def, despite subsequent incrementing,
had the dual faults of assigning the same index to every line and
being inaccessible outside the "def".

I had also tried "if !defined?(indx)" somehow, but that was useless
across multiple invocations of "def".

Again, thanks to you both for your responses.
 

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