Hop*_*eam 53 ruby ruby-on-rails
有没有更好的方法来写这个:
if myarray.include? 'val1' ||
myarray.include? 'val2' ||
myarray.include? 'val3' ||
myarray.include? 'val4'
Run Code Online (Sandbox Code Playgroud)
tok*_*and 98
使用set intersectionctions(Array#:&):
(myarray & ["val1", "val2", "val3", "val4"]).present?
Run Code Online (Sandbox Code Playgroud)
你也可以循环(any?将在第一次出现时停止):
myarray.any? { |x| ["val1", "val2", "val3", "val4"].include?(x) }
Run Code Online (Sandbox Code Playgroud)
这对小型数组来说没问题,在一般情况下你最好有O(1)谓词:
values = ["val1", "val2", "val3", "val4"].to_set
myarray.any? { |x| values.include?(x) }
Run Code Online (Sandbox Code Playgroud)
使用Ruby> = 2.1,使用Set#intersect:
myarray.to_set.intersect?(values.to_set)
Run Code Online (Sandbox Code Playgroud)
创建您自己的可重用方法:
class String
def include_any?(array)
array.any? {|i| self.include? i}
end
end
Run Code Online (Sandbox Code Playgroud)
"a string with many words".include_any?(["a", "string"])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39549 次 |
| 最近记录: |