开发者

Ruby: Using the "index" method with "OR"

开发者 https://www.devze.com 2022-12-18 15:14 出处:网络
Using the index method, I\'m trying to find if a value exists using a certain variable, and if that variable doesn\'t exist, then try another variable; a little something like this (3rd line below):

Using the index method, I'm trying to find if a value exists using a certain variable, and if that variable doesn't exist, then try another variable; a little something like this (3rd line below):

a = [ "a", "b", "c" ]
a.index("b")   #=> 1
a.index("z" or "y" or "x" or "b")   #=> 1

..meaning that if "z" is not found in the array, then try "y"; if y is not found, then try x; if x is not found then try b

How would开发者_C百科 I do that correctly?


TIMTOWTDI. But I prefer using Array#inject.

%w(x y z b).inject(nil) { |i, e| i or a.index(e) } #=> 1

And there is an another way to do this with more similar to your pseudo-code.

class String
  def | other
    ->(e) { self==e || other==e }
  end
end

class Proc
  def | other
    ->(e) { self.call(e) || other==e }
  end
end

a.index(&('x' | 'y' | 'z' | 'b')) #=> 1


Depends on your end goal. If you just want to see if a contains a z, y, x or b, you can do this:

(a & %w{z y x b}).length > 0   # gives true if a contains z, y, x and/or b.

what we're doing is seeing if there is a set intersection where a contains some shared elements with the set of desired quantities, then testing to see if there were any of those elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号