An 'in' operator for Ruby?

I have had two fairly small changes I wanted to make in Ruby. The first was realized years ago -- hashes now preserve insertion order and iterate in a predictable way. That's fairly minor, but it did/does have some use cases, and it had no impact on performance.

Here's another one. Personally, this is a bigger thing to me.

I've always believed personally that Ruby should have an in operator.

I've mentioned this in speaking (including lightning talks) and in writing. It's not a giant big deal for me, but it is one of my personal favorite ideas. Here are some details.

My proposal

I propose to let x in y be syntax sugar for y.include? x

You may ask: Why?

          if barrel.include? rotten_apple        # Is barrel going bad?
          if fruit in [:apple, :pear, :peach]    # Is this fruit something I like?
          if foo == var1        ||
             foo =~ var2        ||
             foo < var3         ||
             var4.include?(foo) ||
             foo > var5

      To quote him as well as I remember: "I was having this perfectly nice conversation
      with foo, and then var4 interrupted it..."

          if [GA, VA, MS, TX, MD, NC].include? state      # ehhhh
          if state in [GA, VA, MS, TX, MD, NC]            # better
          if (10..100).include?  x   # Need parens
          if x in 10..100            # Don't need parens (also prettier)

Frequently Whined Whines

         if mylist    # ugly
         if x.== 5         # also ugly
         if c1.and c2      # ugly (if it worked)

         if x == 5         # better
         if c1 and c2      # better
         if x in mylist    # better
         if my_set   # very ugly
         if x.==? 5         # very ugly (if it worked)
         if item not in collection  # travesty!
         if ! (item in collection)  # ok

         if x not == y              # horrible Ruby travesty (if it worked)

       Yes, I say this even though ! (item in collection) requires parentheses.
       See the comment about parentheses on ranges.


People have ignored me on this for at least ten years. They probably still will. That, as they say, is life.

Back Home