» Abusing Ruby's question mark methods.

I've always enjoyed the ruby convention of using question marks to denote boolean methods. empty?, exist?, any?, alive?, etc... They're concise and easy to read. I do have one gripe with it, sometimes testing the inverse makes my code read like yoda wrote it.
not sting.empty?
not path.file?
not param.blank?
In rails I use not something.blank? a lot, so creating a not_blank? method wrapper around blank? was a nice simple fix. But I'm lazy and easily give into the temptation of the dark side, so I created a Bizarro Object. Which lets me do this...
# Meaningless examples that prove my point

"".not.empty?       #=> false
"words".not.empty?  #=> true

0.not.zero?         #=> false
1.not.zero?         #=> true
And here is the bit of code that makes it work...
class BizarroObject
  # Since this is a proxy, get rid of every default method
  # Copied from Jim Weirich's BlankSlate class
  # http://onestepback.org/index.cgi/Tech/Ruby/BlankSlate.rdoc
  instance_methods.each { |m| undef_method m unless m =~ /^__/ }

  # Takes an object as a parameter and will invert the return values of all it's methods.
  def initialize(object)
    @object = object
  end

  def method_missing(symbol, *args)
    !@object.send(symbol, *args)
  end
end

class Object
  # This is where the proxy/bizarro object is created
  def not
    BizarroObject.new(self)
  end
end
It's not optimized, and it's a little ridiculous, but I love that ruby lets me abuse it like this.

User Comments

Recent Posts

  • Interactive console for iOS! - August 20, 2010
  • Archive

    • Letter to Steve Jobs - April 11, 2010
    • Wax talks to Twitter - October 20, 2009
    • How does iPhone Wax work? - October 19, 2009
    • Setting up iPhone Wax - October 18, 2009
    • Ruby (tinyrb) on iPhone - May 03, 2009
    • Building PCRE static lib for the iPhone - May 02, 2009
    • Amazon EC2 + Chef = Mmmmm - March 29, 2009
    • Objective-c key paths - February 13, 2009
    • POW! - December 26, 2008
    • Abusing Ruby's question mark methods. - November 28, 2008
    • Git hooks make me giddy - November 07, 2008
    • Ruby Equality! equal? eql? == and === - October 26, 2008
    • Ruby, Rails and Google Sitemaps - October 20, 2008
    • Projects

      • Wax Obj-C to Lua bridge for iPhone.
      • Pow a Ruby library for making file & directory manipulation easy.
      • MiniMagick a tiny RMagick replacement.