Ruby-on-rails 使用 .include 检查数组中的多个项目?-- 红宝石初学者

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8026300/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:18:27  来源:igfitidea点击:

Check for multiple items in array using .include? -- Ruby Beginner

ruby-on-railsruby

提问by Hopstream

Is there a better way to write this:

有没有更好的方法来写这个:

if myarray.include? 'val1' ||
   myarray.include? 'val2' ||
   myarray.include? 'val3' ||
   myarray.include? 'val4'

回答by tokland

Using set intersections (Array#:&):

使用集合交集(Array#:&):

(myarray & ["val1", "val2", "val3", "val4"]).present?

You can also loop (any?will stop at the first occurrence):

您还可以循环(any?将在第一次出现时停止):

myarray.any? { |x| ["val1", "val2", "val3", "val4"].include?(x) }

That's ok for small arrays, in the general case you better have O(1) predicates:

这对于小数组来说没问题,在一般情况下,你最好有 O(1) 谓词:

values = ["val1", "val2", "val3", "val4"].to_set
myarray.any? { |x| values.include?(x) }

With Ruby >= 2.1, use Set#intersect:

使用 Ruby >= 2.1,使用Set#intersect

myarray.to_set.intersect?(values.to_set)

回答by Jeremy Lynch

Create your own reusable method:

创建您自己的可重用方法:

class String
  def include_any?(array)
    array.any? {|i| self.include? i}
  end
end

Usage

用法

"a string with many words".include_any?(["a", "string"])