In Ruby why won't `foo = true unless defined?(foo)` make the assignment?

后端 未结 7 929
悲哀的现实
悲哀的现实 2020-12-03 14:48

What\'s going on here? What is the subtle difference between the two forms of \"unless\"?

> irb(main):001:0> foo = true unless defined?(foo)
=> nil         


        
7条回答
  •  自闭症患者
    2020-12-03 14:53

    Apparently, ruby creates local variable at parse time setting them to nilso it is defined and this is done whether the code is executed or not.

    When the code is evaluated at your first line, it doesn't execute the assignment part since foo is set to nil. In the second line, because fooo has not been parsed yet, defined?returns nil letting the code inside the block execute and assign fooo.

    As an example you can try this:

    if false  
      foo = 43  
    end  
    defined? foo  
    => "local-variable"
    

    This is taken from a forum post at ruby-forum.

提交回复
热议问题