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

怎甘沉沦 提交于 2019-12-01 16:51:51

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.

Femaref

Use the || operator in this case:

@c = amount || r (1,4)

In your code, the defined? method operates on amount ? amount : r( 1,4 ) instead of just on amount as you intended. Also, the defined? operator probably doesn't do what you expect, have a look at this blog entry to get an idea.

You're looking for the null coalescing operator. Try this:

@c = amount || r(1,4)

This code will assign amount to @c if amount is defined. If not it will assign the result of r(1,4) to @c.

http://eddiema.ca/2010/07/07/the-null-coalescing-operator-c-ruby-js-python/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!