Last Updated: February 25, 2016
·
1.627K
· eladmeidar

Better Ruby inclusion methods

It always bothered me that the #include? method in ruby treats the container (in this case, an array) as the subject of the method. in my own distorted mind it was weird not to think of the element i'm looking for as the subject.
So i did this:

module ReverseInclude

  def self.included(base)
    base.class_eval do
      extend ClassMethods
      include InstanceMethods
    end
  end

  module InstanceMethods  
    def included_in?(arr = [])
      arr.include?(self)
    end

    def not_included_in?(arr = [])
      !(included_in?(arr))
    end
  end

  module ClassMethods
  end
end

Object.send(:include, ReverseInclude)

a short and happy little module (Backfires into Object as you can see) and adds the #included_in? and the #notincludedin? methods to every object in the system and basically allows the following:

@item.included_in?(array)

and

@item.not_included_in?(array)

Initially i thought about extending the Enumerable module but for now it seemed to be enough just to expose those methods in a standalone module.