Duck Typing Situations To Save Code

Some of you may have run into a situation where you used is_a? and kind_of? to determine the types of certain objects. I wanted to refer to an article by Jay Fields on the topic which covers a simple case of duck typing.

def columns(*args)
  args.each |element|
    @column_array << element.to_sql
  end
end

Clearly, for this example to work each argument must respond to the to_sql method. Because Ruby's classes can be re-opened this change is trivial.

class String
  def to_sql
    "'#{self}'"
  end
end

class Fixnum
  def to_sql
    self
  end
end

class Symbol
  def to_sql
    self.to_s
  end
end

Of course you can reference the Programming Ruby book as well.