Clean file separators in Ruby without File.join

Posted by kerry on Gooder Code See other posts from Gooder Code or by kerry
Published on Mon, 15 Feb 2010 22:20:53 +0000 Indexed on 2010/03/18 23:21 UTC
Read the original article Hit count: 410

Filed under:
|

I love anything that can be done to clean up source code and make it more readable.  So, when I came upon this post, I was pretty excited.  This is precisely the kind of thing I love.

I have never felt good about ‘file separator’ strings b/c of their ugliness and verbosity.

In Java we have:

   1: String path = "lib"+File.separator+"etc";

And in Ruby a popular method is:

   1: path = File.join("lib","etc")

Now, by overloading the ‘/’ operator on a String in Ruby:

   1: class String

   2:   def /(str_to_join)

   3:     File.join(self, str_to_join)

   4:   end

   5: end

We can now write:

   1: path = 'lib'/'src'/'main'

Brilliant!

© Gooder Code or respective owner

Related posts about Developer Tools

Related posts about ruby