Skip to: Site menu | Main content

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.

2 Responses to “Cute method_missing hack”

  1. o Says:

    Oh, god.

    Ruby’s the next pink, innit?

  2. Tal Rotbart Says:

    LOL, you’re late to the game!

    Ruby was the next pink a year ago, now Scala is the next Ruby. Well not really, but close.

Leave a Reply