Ruby - 是否有针对一个变量的两个逻辑条件的速记检查

时间:2018-02-27 18:26:28

标签: ruby

如何缩短此表达式?

if artist != 'Beck' && artist != 'Led Zeppelin'
  5.times { puts 'sorry' }
end

是否有针对一个变量的两个逻辑条件的速记检查?

顺便说一下,这变成了

class String
  def is_not?(*arr)
    !arr.include?(self)
  end
end

在我们的项目中。

现在我们可以'foo'.is_not?('bar', 'batz')

3 个答案:

答案 0 :(得分:3)

unless ['Beck', 'Led Zeppelin'].include?(artist)
  5.times { puts 'sorry' }
end

不是任何“更短”,但也没有模糊的语法技巧。只需使用常规数组api。因此,您可以以任何方式提供该数组。例如,从文件加载它。任意数量的元素。

答案 1 :(得分:1)

您的具体情况非常少,但如果您有许多不相关的条件来测试大量值,您可以将测试设置为数组中的lambda并使用all?。例如,以下示例过滤了>之间的所有1到100之间的整数。 20,< 50,偶数,可被3整除:

tests = [
  ->(x) { x > 20 },
  ->(x) { x < 50 },
  ->(x) { x.even? },
  ->(x) { x % 3 == 0 }
]

(1..100).each do |i|
  puts i if tests.all? { |test| test[i] }
end

答案 2 :(得分:0)

case artist
when 'Beck', 'Led Zeppelin'
else
  5.times { puts 'sorry' }
end
相关问题