Ruby: method inexplicably overwritten and set to nil

If I execute this ruby ​​code:

def foo 100 end p defined?(foo), foo if false foo = 200 end p defined?(foo), foo 

The output I get is:

 "method" 100 "local-variable" nil 

Can someone explain to me why foo set to nil after not executing if? Is this the expected behavior or ruby ​​error?

+7
source share
2 answers

The names on the left side of the assignments are set to nil , even if the code cannot be reached, as in the case if false .

 >> foo NameError: undefined local variable or method `foo' for main:Object ... >> if false .. foo = 1 .. end #=> nil >> foo #=> nil 

When Ruby tries to resolve simple words, it first searches for local variables (there is a link to something in Pickaxe's book that I cannot find yet). Since you now have one called foo , it displays nil . As Misha noted, the method can still be called foo() .

+5
source

This is what my buddy and super-specialist Junior Josh Chick had to say:

When Ruby sees the assignment, it initializes the variable in the current scope and sets it to nil. Since the assignment did not start, it did not update the value of foo.

If statements do not change the scope, how blocks do. This is also the most important difference between

 for x in xs 

and

 xs.each { |x| } 

Here is another example:

 a = 123 if a # => nil a # => nil 

We cannot say if a , because we never set a , but Ruby sees a = 123 and initializes a , then goes to if a , at which point a is nil

I would consider this a fad translator. Gary Bernhardt makes fun of him at wat ( https://www.destroyallsoftware.com/talks/wat ) with a = a

-Josh

+1
source

All Articles