ruby interpreter: when is a variable defined?

时间:2018-02-05 12:58:32

标签: ruby

I noticed a pretty odd behaviour in a ruby irb console. If I execute:

irb(main):001:0> defined?(a)
=> nil    
irb(main):002:0> a = true if defined?(a)
=> true
irb(main):003:0> a
=> true

since I haven't defined a and defined?(a) returns false I would expect a = true to not be executed. But that's not the case and a = true is actually executed and a has value true.

This can be simplified to

irb(main):001:0> a = "hello" if false
=> nil
irb(main):002:0> defined?(a)
=> "local-variable"

What I thought at the beginning is that a is defined before checking the condition but converting this into:

irb(main):001:0> (a = "hello") if false
=> nil
irb(main):002:0> defined?(a)
=> "local-variable" 

Who can explain this behaviour to me? How does ruby evaluate such statement?

if false
  a = "hello"
end

defined?(a) # true

1 个答案:

答案 0 :(得分:3)

It has nothing to do with defined?. It seems the parser needs to define that variable in advance if there's a chance it needs that. Check this

a
NameError (undefined local variable or method `a' for main:Object
a = 4 if false
nil
a
nil