tags:

views:

90

answers:

3

Python has really elegant syntax for checking a value against several patterns.

2 in [1,2,4] #=> True
6 in [1,2,4] #=> False

Order in Ruby version just feels wrong:

[1,2,4].include?(2)

I understand that include? makes a lot more OO sense than 2.included_in?([1,2,4]), I still don't like it. Ruby even has in keyword but it seems to only be used in construct for i in [1,2,4], not for membership tests.

Another way is this:

(case 2 when 1,2,4 then true end)

Quite verbose, but allows patterns test:

(case file_name when "README", /\.txt\z/ then true end)

Still not very readable.

Am I missing some really nifty way by chance?

+3  A: 

I guess that the benefit of introducing "more common" pattern was not worth burdening the language with a new syntax construct with very specific use, especially because using .include? is neither tedious, nor counter-intuitive, when you think of it.

On the other hand, what prevents you from implementing and using Object#included_in? method?

Mladen Jablanović
+6  A: 

As @deceze says, you can implement your own:

class Object
  def in(ar)
    ar.include? self
  end
end

irb(main):013:0> 's'.in ['a', 'b', 'c']
=> false
irb(main):014:0> 's'.in ['a', 'b', 'c', 's']
=> true
irb(main):015:0> 5.0.in [3.2, 5.0, 1.2]
=> true
irb(main):016:0> 4.0.in [3.2, 5.0, 1.2]
=> false
ngoozeff
Just a small suggestion: the method should be named `in?`, which is kind of a convention for Ruby methods returning boolean values.
Mladen Jablanović
+1  A: 

$ gem install sane

$ irb

 >> 3.in? [1,2,3]
 >> true
rogerdpack