如何缩短同样令人满意的条件

时间:2016-07-27 07:42:55

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我怎样才能使条件变得更好,因为它具有同样满足大于零的条件。以下是代码:

a = 10
b = 5
c = 2

if a > 0 || b > 0 || c > 0
  puts "greater that zero"
else
  puts "it is zero or less than zero"
end

3 个答案:

答案 0 :(得分:4)

我可能会这样做

if [a, b, c].any? { |x| x > 0 }
  puts "greater that zero"
else
  puts "it is zero or less than zero"
end

答案 1 :(得分:3)

怎么样:

if [a, b, c].max > 0
  puts "greater that zero"
else
  puts "it is zero or less than zero"
end

答案 2 :(得分:2)

我喜欢使用三元运算符来表示真或假的情况。

[a,b,c].any?(&:positive?) ? "greater that zero" : "it is zero or less than zero"

一些例子: https://repl.it/CgZR/1