From: John Feminella Date: 2011-02-25T15:17:47+09:00 Subject: Re: parsing rule for this code? As a rule of thumb, variables exist until you reach the "end" or closing brace of the innermost block that they're still contained in. In your case, you have this: >    def do_something >        3.times do |x| >            number = 10 >        end >        puts number >    end The local variable `number` is created with the value 10 and then immediately discarded. This happens three times, since the block executes three times. The goal of the next statement is to print a local variable called `number`. But there is no such local variable in this block. So Ruby rightfully complains that you didn't define it. If instead you had written this: >    def do_something > number = 0 # create `number` in this lexical scope >        3.times do |x| >            number = 10 >        end >        puts number >    end then it would work as you probably expect. ~ jf -- John Feminella Principal Consultant, BitsBuilder LI: http://www.linkedin.com/in/johnxf SO: http://stackoverflow.com/users/75170/ On Thu, Feb 24, 2011 at 22:41, 7stud -- wrote: > 1) > class ABC >    def do_something >       number = 10 >       puts number >    end > end > > ABC.new.do_something > > --output:-- > 10 > > > 2) > class ABC >    def do_something >        3.times do |x| >            number = 10 >        end >        puts number >    end > end > > ABC.new.do_something > > --output:-- > Line 6:in `do_something': undefined local variable or method `number' > for # (NameError) >  from t.rb:10 > > > Why does ruby get confused by the setter v. local variable assignment > when adding a block? > > -- > Posted via http://www.ruby-forum.com/. > >