Slashing File.join in Ruby

If you’re doing some file system manipulations in Ruby, moving and creating files around (which it does very well as it doesn’t try to ignore, like Java, that there is a file system) you have basically two choices: hard code a lot of ‘/’ characters in your code, which isn’t pretty, or use File.join. After a while you end up with many of these joins all over the place and it’s not so pretty (there’s actually a third possibility, you can directly use File::SEPARATOR, but it’s so ugly that I’m not counting it).

Yesterday, I had this really simple idea:

class String
def /(str_to_join)
File.join(self, str_to_join)

It’s so sweet and easy that I can’t even figure why I’ve never thought of it before. Now I can do:

'tmp'/'readme.txt' # literals
ROOT_DIR/file_path # variables holding strings

Much easier on the eyes and the fingers.


No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: