[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: evaluation order

e

2/13/2005 2:03:00 PM

> Lähettäjä: "David A. Black" <dblack@wobblini.net>
> Aihe: Re: evaluation order
>
> Hi --
>
> On Sun, 13 Feb 2005, Robert Klemme wrote:
>
> >
> > "Zehao" <zehao.chen@gmail.com> schrieb im Newsbeitrag
> > news:1108274165.071278.164610@z14g2000cwz.googlegroups.com...
> >> One interesting thing is when running the following codes
> >>
> >> File.open("testfile") |aFile| do
> >> print a while a=aFile.gets
> >> end
> >>
> >> one will get an error indicating a doesn't exist. This error can be
> >> fixed by adding a line a="" before the print command.
> >>
> >> But logically speaking, "print a" should be interpreted after
> >> "a=File.gets". Is this because the interpreter couldn't find the object
> >> "a" when first scanning the second line?
> >
> > I suspect it's the same issue as with local variables: Ruby applies a certain
> > heuristic to determine whether something is a local var or not. This
> > heuristic is based on *syntactical* order of occurrence
> >
> >>> def foo
> >>> print a
> >>> a = 10
> >>> end
> > => nil
> >>> foo
> > NameError: undefined local variable or method `a' for main:Object
> > from (irb):2:in `foo'
> > from (irb):5
>
> It's also fun to see what happens if you run this kind of thing twice:
>
> irb(main):005:0> puts x if x = 1
> NameError: undefined local variable or method `x' for main:Object
> from (irb):5
> irb(main):006:0> puts x if x = 1
> 1
>
>
> (For clarity I've deleted the warning about using '=' in conditional.
> [Matz, can't we get rid of that warning?])

In general that's a useful warning... I'm assuming you may mean just
in a context where the statement modifier assigns to the variable?

> David

E