From: John Feminella Date: 2011-02-26T10:06:19+09:00 Subject: Re: parsing rule for this code? The parser does not think `number` is a method by virtue of writing "puts number". It tries to invoke a method called number because there is no local variable named number, because the local variable that you named `number` is no longer in scope. To see this for yourself, consider this snippet: number = 10 def number 20 end puts number # => 10 Notice Ruby correctly picks the local variable named `number`, not the method called `number`. ~ jf -- John Feminella Principal Consultant, BitsBuilder LI: http://www.linkedin.com/in/johnxf SO: http://stackoverflow.com/users/75170/ On Fri, Feb 25, 2011 at 19:40, 7stud -- wrote: > John Feminella wrote in post #983784: >> 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. > > > Actually, I think the parser determines that 'number' in the line: > >  puts number > > is a method.  See this code: > > class Dog > >  def method_missing(name, *args) >    puts "*** #{name.to_s} ***" >    super >  end > >  def test >     3.times do >       number = 10 >       puts number >     end > >     puts number >  end > end > > Dog.new.test > > > --output:-- > 10 > 10 > 10 > *** number *** > > Line 5:in `method_missing': undefined local variable or method `number' > for # (NameError) >  from t.rb:14:in `test' >  from t.rb:18 > > -- > Posted via http://www.ruby-forum.com/. > >