Why should this statement work?

Dear Ruby gurus,

I typed my way to this interesting code

         a = a

Why should the above statement be valid, although a was not predefined
prior to
the assignment?

Ruby version is ruby 1.9.3p125

saji

Saji N Hameed,
ARC-ENV, Center for Advanced Information Science and Technology,
University of Aizu, Tsuruga, Ikki-machi,
Aizuwakamatsu-shi, Fukushima 965-8580,
Japan

Tel: +81242 37-2736
Fax:+81242 37-2760
email: [email protected]
url: http://enformtk.u-aizu.ac.jp
bib: http://www.researcherid.com/rid/B-9188-2009
code: https://github.com/sajinh

On Wed, Apr 9, 2014 at 7:24 AM, Saji H. [email protected] wrote:

Dear Ruby gurus,

I typed my way to this interesting code

         a = a

Why should the above statement be valid, although a was not predefined prior
to the assignment?

A local variable is valid from the first point in the surrounding
scope where it is assigned. Since the assignment (left hand side of
the expression) comes before the evaluation (right hand side) it is
completely legal. That rule has also other consequences:

$ ruby -e ‘puts a if a=1’
-e:1: warning: found = in conditional, should be ==
-e:1:in <main>': undefined local variable or methoda’ for
main:Object (NameError)

Execution order is different than textual order but that’s the way it
is.

Kind regards

robert

Robert, Thanks a lot for the explanation - it makes sense now !

saji

Saji N Hameed,
ARC-ENV, Center for Advanced Information Science and Technology,
University of Aizu, Tsuruga, Ikki-machi,
Aizuwakamatsu-shi, Fukushima 965-8580,
Japan

Tel: +81242 37-2736
Fax:+81242 37-2760
email: [email protected]
url: http://enformtk.u-aizu.ac.jp
bib: http://www.researcherid.com/rid/B-9188-2009
code: https://github.com/sajinh