Now you can use obj.in?(array) instead of array.include?(obj)

I just wrote a tiny gem called in_enumerable. It extends Ruby’s Object type with the tasty ‘in?’ method, which returns true if an object is included in a list or other enumerable value.

So you can do this:


1.in? [1,2]          # => true
3.in? [1,2]          # => false

instead of the slightly more awkward:


[1,2].include?(1)    # => true
[1,2].include?(3)    # => false

Despite its name, in_enumerable doesn’t require an enumerable type.  It uses duck typing to work with any type that has an ‘include?’ method, such as Array, Hash, String, Range, Set, and even Module.

Installation


gem install in_enumerable

Usage


require 'rubygems'
require 'in_enumerable'

Side Note

I noticed that typing ri Object#in? reveals that a similar method supposedly already exists on the Object type. And if you google it you can find the source code for it. (It’s almost the same as mine.) But it doesn’t actually seem to be implemented, at least not in Ruby 1.8.6. So I made my own.

6 thoughts on “Now you can use obj.in?(array) instead of array.include?(obj)”

  1. Nifty. Small (well, I haven’t seen the source, don’t hate me) projects like these that helps with tiny annoyances always make me happy. Less is more mostly accurate in coding. This doesn’t even sacrifice any readability, I think it improves it!

  2. Object#in? must be defined in some gem you have installed. Perhaps rails? facets? extensions?

    It’s unfortunate that ri doesn’t tell you where it’s defined.

  3. Hi Gavin, Object#in? is what this post is about. Take a look again at the post and you’ll see how to install it. If it still doesn’t work or something’s unclear, please do let me know.

  4. The reason for my comment above is this: “I noticed that typing ri Object#in? reveals that a similar method supposedly already exists on the Object type.”

    I realise you’ve implemented it yourself — and commend you on your good taste! — but it existed on your system beforehand (as evidenced by ri) and I was just suggesting why that might be.

    There’s been discussion in the distant past about including this method in core Ruby. I’d be a fan of that.

  5. Ah, now I see what you were saying. Yeah, I’d be a fan of Object#in? being defined in core Ruby too. In the meantime, since ri doesn’t make it clear where it’s defined or if it’s even defined at all, I guess my gem will do for now.

Leave a Reply

Your email address will not be published. Required fields are marked *

Feel free to use <a>, <b>, <i>, <strong>, <em>, <strike>, <code>.

Code blocks:
[code language="ruby/javascript/html/css/sass/bash"]
[/code]