Clean file separators in Ruby without File.join
- by kerry
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!