Tutorial :Ruby equivalent of foo in [one, two, three]?


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:


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?


$ gem install sane

$ irb

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


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  


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?

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »