26
March
2008

Easier path construction using overloaded /3

At long last I found a justifiable use for operator overloading. Recently I’ve been writing quite a bit of rake files which involved a lot of path construction, like

 path = "#{all}/#{along}/#{the}/#{watch}/#{tower}"

Noticing all those extra characters required to create the path string I realized that the / operator can used for concatenation in this specific use case

class String
  def /(other)
    File.join(self,other)
  end
end

and then we can write a much cleaner version

 path = all/along/the/watch/tower

I wouldn’t advocate the usage outside of a rake file or other path construction intensive code, but for these specific scenarios it is pretty sweet.

Also posted on dzone snippets