[Leaplist] ruby stuff..

Steve Litt slitt at troubleshooters.com
Fri Mar 9 08:54:14 EST 2007


On Friday 09 March 2007 03:17, Fred Moore wrote:
> Ok all of you ruby guys and gals..  It seems I don't understand something
> about variables and scope.. inside ruby..   Just started playing with it..
>
> I have found several references that say that you don't need to define a
> variable.  they get defined the first time they are used..   Perhaps
> something happens differently to variable scope inside a block..  anyway I
> am confused.. perhaps someone can help me  out..  and educate this poor
> fool.. 3 books don't seem to explain the problem..   google tells me to
> quit bothering it.
>
> the following code snipit runs just fine..   and outputs each line with a
> line number before it..
>
> -----------------------------------------------------
> #!/usr/bin/ruby -w
> file = File.new("buildFile.tex", "r")
> counter=0
> while (l = file.gets)
> 	puts "#{counter}:#{l}"
> 	counter +=1
> end
> file.close
> -----------------------------------------------------
>
> this next snipit blows up with a
>
> "undefined local variable or method `all'  for main:Object (Name Error)"
>
> all that is added is line 5 all[counte]=l, I want to spin an array of lines
> from the file..
>
> ----------------------------------------------------
> #!/usr/bin/ruby -w
> file = File.new("buildFile.tex", "r")
> counter=0
> while (l = file.gets)
> 	all[counter]=l
> 	puts "#{counter}:#{l}"
> 	counter +=1
> end
> file.close
>
> ---------------------------------------------------
>
>  so who can explain this behavior.. Fred

I can, to a degree. Strings and integers don't need initializing, but arrays 
and hashes do. So do one of these:

all = []
all = Array.new

I think automatic declaration works only for scalars.

SteveT


More information about the Leaplist mailing list