Ruby-on-rails 如何“轻松”/“有效”检查`Integer`是否大于另一个`Integer`?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11869332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a `Integer` is greater than another `Integer` "easily" / "efficiently"?
提问by user12882
I am using Ruby on Rails 3.2.2 and I would like to check if a Integeris greater than 0and, more in general, if a Integeris greater than another Integer.
我正在使用 Ruby on Rails 3.2.2,我想检查 aInteger是否大于0,更一般地说,如果 aInteger大于另一个Integer。
There is some Ruby or Ruby on Rails methodto make that "easily" / "efficiently"?
是否有一些 Ruby 或 Ruby on Rails方法可以“轻松”/“高效”地做到这一点?
Note: I would like to use / state that methodin my view files and I think, if that method do not "exist", it could be better to state a "dedicated" method in my model or controller file and use that method in my views.
注意:我想在我的视图文件中使用 / state 该方法,我认为,如果该方法不“存在”,最好在我的模型或控制器文件中声明一个“专用”方法并在我的看法。
回答by Daniel Evans
Whenever I start comparing more than two integers, I usually revert to array#max.
每当我开始比较两个以上的整数时,我通常会恢复到 array#max。
a = 1
b = 2
[0, a, b].max == a # false
a = 3
[0, a, b].max == a # true
The primary weakness of this is if a == b, so a special check is required for that case. Or you can do:
这样做的主要弱点是如果 a == b,因此需要对这种情况进行特殊检查。或者你可以这样做:
[0, a, b + 1].max == a
or
或者
[0, a, b].max == a && a != b
EDIT: This method would probably fit best in your helpers.
编辑:此方法可能最适合您的助手。
回答by Florian
As shown here:
如图所示在这里:
a = (print "enter a value for a: "; gets).to_i
b = (print "enter a value for b: "; gets).to_i
puts "#{a} is less than #{b}" if a < b
puts "#{a} is greater than #{b}" if a > b
puts "#{a} is equal to #{b}" if a == b
You can use standard Ruby within your views between <%and %>. And yes, you could implement a helper do to the check and use that helper method in your view.
您可以在<%和之间的视图中使用标准 Ruby %>。是的,您可以实现一个辅助方法来检查并在您的视图中使用该辅助方法。

