[ruby-core:81009] [Ruby trunk Bug#13543][Rejected] local variable declaration

From: duerst@...
Date: 2017-05-06 00:15:14 UTC
List: ruby-core #81009
Issue #13543 has been updated by duerst (Martin D端rst).

Status changed from Open to Rejected

As far as I understand, the detection of variables (and as a consequence the shadowing of methods with the same name) occurs in lexical order. That means that because in

```
foo = foo.size
```

the variable name comes before the method call, the second `foo` is already shadowed. Something similar also happens in e.g.

```
foo = 5 if foo.size > 10
```

Here, it's even more clear that the if is evaluated first (and the assignment maybe never), but still, the variable is lexically earlier, and so the method is shadowed. See also https://bugs.ruby-lang.org/issues/1141 and other bug reports linked from there.

----------------------------------------
Bug #13543: local variable declaration
https://bugs.ruby-lang.org/issues/13543#change-64668

* Author: eiko (eiko kokuma)
* Status: Rejected
* Priority: Normal
* Assignee: 
* Target version: 
* ruby -v: 2.4.0rc1
* Backport: 2.2: UNKNOWN, 2.3: UNKNOWN, 2.4: UNKNOWN
----------------------------------------
The following code snippet generates a strange error:

~~~ ruby
def foo
  @foo ||= "foo"
end

foo = foo.size

#=> undefined method 'size' for nil:NilClass (NoMethodError)
~~~

I expect the code to create a local variable `foo` which is assigned the value `3`. I expect this because in assignment, the right size of `=` is always resolved before being bound to the left side of `=`. In my mind, `foo` should refer to the `foo()` method right up to the point that a value is assigned to the local variable which shadows it. It is confusing and unexpected to have a period of limbo in which `foo()` is overshadowed by an unassigned local variable mid-declaration.

In other languages, declaration and initial assignments are atomic, so this code would throw errors:

In python:

~~~ python
foo = foo
# NameError: name 'foo' is not defined
~~~

In rust:

~~~ c
let foo = foo
// error: cannot find value 'foo' in this scope.
~~~

But in ruby, a variable can be instantly declared and assigned to itself:

~~~ ruby
foo = foo
#=> nil
~~~

This goes against the common motifs of programming in ruby and other languages and can lead to the confusing error mentioned above. Is there a reason local variables should be declared prior to resolving the assignment expression in ruby? I could find no documented reason for this design choice, leading me to believe it is a bug.



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>

In This Thread

Prev Next