Cute method_missing hack

I love abusing method_missing in Ruby, it is great fun.

 module IsDoesIsntDoesnt

  def method_missing(method, *args)
    m = method.to_s
    if (m =~ /^is_(\w*?\?)$/) || (m =~ /^does_(\w*?\?)$/)
      real_method = $1.to_sym
      return send(real_method, *args) if respond_to?(real_method)
    elsif (m =~ /^isnt_(\w*?\?)$/) || (m =~ /^doesnt_(\w*?\?)$/)
      real_method = $1.to_sym
      return !send(real_method, *args) if respond_to?(real_method)
    elsif (m =~ /^(\w*?)s\?$/)
      real_method = "#{$1}?".to_sym
      return send(real_method, *args) if respond_to?(real_method)
    end
    super.method_missing(method, *args)
  end

end

Object.class_eval() do
  include IsDoesIsntDoesnt
end

Which lends itself to these types of natural statements:

?> "team".includes?("i")
=> false
>> "team".isnt_empty?
=> true

and:

>> [].is_empty?
=> true
>> [ :stuff ].does_include?(:stuff)
=> true

While I’m sure Ruby mavens will think of much nicer ways to implement this type of functionality, I had fun doing it.

An exercise for the reader would be to dynamically add the appropriate method, so the next call doesn’t rely on method_missing.