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

后端 未结 7 948
悲哀的现实
悲哀的现实 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 15:04

    in the first instance you call foo into existence in the assignment statement. Maybe this will clarify:

    bar = if true
             puts bar.class
          else
             puts "not reached"
          end
    NilClass
    => nil
    
    baz = if true
             puts baz.class
             42
          else
             puts "not reached"
          end
    NilClass
    => 42
    

提交回复
热议问题