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: saji@u-aizu.ac.jp
url: http://enformtk.u-aizu.ac.jp
bib: http://www.researcherid.com/rid/B-9188-2009
code: https://github.com/sajinh

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 method `a' for
main:Object (NameError)

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

Kind regards

robert

···

On Wed, Apr 9, 2014 at 7:24 AM, Saji Hameed <saji@u-aizu.ac.jp> 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?

--
[guy, jim].each {|him| remember.him do |as, often| as.you_can - without end}
http://blog.rubybestpractices.com/

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: saji@u-aizu.ac.jp
url: http://enformtk.u-aizu.ac.jp
bib: Web of Science
code: sajinh (Saji Hameed) · GitHub

···

On Wed, Apr 9, 2014 at 2:34 PM, Robert Klemme <shortcutter@googlemail.com>wrote:

On Wed, Apr 9, 2014 at 7:24 AM, Saji Hameed <saji@u-aizu.ac.jp> 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 method `a' for
main:Object (NameError)

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

Kind regards

robert

--
[guy, jim].each {|him| remember.him do |as, often| as.you_can - without
end}
http://blog.rubybestpractices.com/