From: Paul Brannan Date: 2002-01-31T06:30:43+09:00 Subject: Re: test for presence in array On Thu, Jan 31, 2002 at 05:44:29AM +0900, Kamil Kukura wrote: > I ran into typical situation where I needed to test number x against a > couple of values. What entered my mind is: > > [10, 20, 100, 500].include?(x) > > I like it but I think I would prefer to have x.in? [10, 20, 100, 500] > I guess it could go into Comparable module. Or is there better /nicer/ way? If you already have an array, then your solution works, but is an O(n) operation. If you are concerned about speed, then you can use a hash: if {1=>true, 2=>true, 3=>true, 4=>true}.include?(x) then # do stuff end Not the nicest syntax in the world, but it works. There are also a number of nice Set classes out there that do the same thing with a cleaner syntax. As far as your question goes, I don't think it really makes sense for a contained item to know about a container. That is, a Fixnum should not have to have any knowledge of the Array in which it is stored. x.in?(y) could call y.include?(x), but this assumes a specific interface for y (that is, it assumes y has a method called include?). In the end, both are equally readable, and the solution Ruby uses now is slightly less complex. Paul