tags:

views:

68

answers:

2

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 I do that correctly?

+2  A: 

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.

Peter
Thanks Peter. It works perfectly. Thank you so much :)
andy
+2  A: 

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
nwn
Thank you nwn! I really appreciate the great help :) Thanks so much for the clear explanation.
andy
requires ruby 1.9 for the `->` lambda syntax.
glenn jackman
nwn
@glenn Yes, But In this case I think you can use this in 1.8.x with replacing `->(){}` with `lambda{}` in this case.
nwn