From: Ilan Berci Date: 2008-02-03T09:27:00+09:00 Subject: Re: Why is my var undefined? Tim wrote: > I'm new to ruby and I have the following code: > > index=0 > unsorted_array.each do |value| > if index==0 > smallest=value > smallest_index=0 > elsif value smallest=value > smallest_index=index > end > index=index+1 > end > > When it gets to index 1, it crashes and says that smallest is > undefined (on the elsif line). Why is that, when it gets defined in > the first pass (index = 0) ? > > Thanks for helping a newbie out. > > Tim It's only defined for the scope that it's in.. which is the "if" block.. Once it leaves that block and your code returns to the "unsorted_array.each" scope, "smallest" is out of scope and therefore no longer defined. Dave Thomas has a free online version of Ruby 1.6 referred as the Pick Axe book which discusses scope and I think you will find it very useful hth ilan -- Posted via http://www.ruby-forum.com/.