Ternary expression with “defined?” returns “expression” instead of value?

前端 未结 3 919
抹茶落季
抹茶落季 2021-01-18 04:53

I\'m pretty new to Ruby and Rails but even after searching stack overflow and google I couldn\'t find an answer to this.

I\'ve got a simple Ruby shorthand if stateme

3条回答
  •  悲哀的现实
    2021-01-18 05:47

    defined? is binding to amount ? amount : r(1,4) so it is equivalent to:

    defined?(amount ? amount : r(1,4))
    

    You probably want:

    defined?(amount) ? amount : r(1,4)
    

    Actually, odds are that amount || r(1,4), or amount.nil? ? r(1,4) : amount would better match what you want, since I think you don't want this:

    1.9.3p194 :001 > defined?(amount)
     => nil 
    1.9.3p194 :002 > amount = nil
     => nil 
    1.9.3p194 :003 > defined?(amount)
     => "local-variable" 
    

    ...in which case @c would be nil - the value of the defined variable.

提交回复
热议问题