具有“定义的”的三进制表达返回“表达式”而不是价值? [英] Ternary expression with "defined?" returns "expression" instead of value?

查看:132
本文介绍了具有“定义的”的三进制表达返回“表达式”而不是价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很喜欢Ruby和Rails,但即使在搜索堆栈溢出和google之后,我也找不到答案。



我有一个简单的Ruby简写if语句应该返回一个整数像这样:

  #在这个erb文件的上下文中,amount被定义为5. 
@c =(定义?amount?amount:r(1,4))
pre>

r()是一个自定义帮助函数,在这种情况下返回之间的随机数 1和4。



我打算这样工作的方式是 if 金额被定义,然后使用定义为金额的数量 else 生成一个随机数字在1到4之间,并使用它。



当打印出 @c 但是Ruby输出表达式而不是一个数字。



我要做什么来让这个工作按照我的意图,我做错了什么?



非常感谢您阅读!

解决方案

定义?是否绑定到金额?金额:r(1,4)所以相当于:

 金额:r(1,4))

你可能想要:

 定义?(金额)?金额:r(1,4)

其实,赔率是 amount | | r(1,4) amount.nil? ? r(1,4):amount 会更好地匹配你想要的,因为我认为你不想要这样:

 
1.9.3p194:001>定义?(金额)
=> nil
1.9.3p194:002> amount = nil
=> nil
1.9.3p194: 003>定义?(金额)
=>局部变量

...在这种情况下 @c 将是 nil - 定义变量的值。


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 statement that should return an integer like so:

# in the context of this erb document `amount` is defined as 5.
@c = ( defined? amount ? amount : r( 1,4 ) )

r() is a custom helper function that returns a random number between in this case 1 and 4.

The way I intend this to work is that if amount is defined, then use the number defined as amount, else generate a random number between 1 and 4 and use that instead.

When printing out @c however Ruby outputs expression rather than a number.

What do I have to do to get this working as I intended and what am I doing wrong?

Many thanks for reading!

解决方案

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.

这篇关于具有“定义的”的三进制表达返回“表达式”而不是价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆