Creating File Paths the Easy Way

The Traditional Way

The traditional way to create file paths that are cross platform in Ruby, was to join them up as arguments in a File.join call:

Result:

"./../../config/database.yml"

Now thats all nice and everything but if you want to change it, you would have the inconvenience of having to add or remove commas, or single|double quotes, which can be a bit of a hassle.

Prettying it Up

So how about we pretty it up a little?

Result:

"./../../config/database.yml"

Now doesn’t that look a whole better?

What in the world is %w[...]?

Why does this work just as well?

The %w[...] creates an array of Strings separated by the whitespaces in the list.

Result:

["..", "..", "config",  "database.yml"]

But what if you have a space in the file name? Well you can use a backslash as an escape key and presto!

Result:

["..", "..", "config",  "a file"]

Note: I’m not so sure what this operator is called, and any help giving it a name would be greatly appreciated.

This entry was posted in Ruby. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. Posted 17 November, 2007 at 11:38 pm | Permalink

    This snippet is related but not exactly trying to solve the same problem: http://snippets.dzone.com/posts/show/2447.

  2. Posted 7 December, 2007 at 8:55 am | Permalink

    Hey, I have to say great blog! I also read your story about how you got started with OSS and your programming career. I can completely relate!

    Anyway… I’m not sure of the operator name either, but recently I was re-writing Dr Nic’s “gitify” script on DZone snippets and I made great use of %{ }. I used %{ } to build my strings into a Ruby one-liner that was converted into a shell command alias. I had to watch my single and double quotes usage, since I was fitting this Ruby into an alias definition (code was already within double/single quotes)…

    http://snippets.dzone.com/posts/show/4813

    BTW: Add our blog to your reader, and keep up the great posts!

  3. Posted 15 December, 2007 at 1:14 pm | Permalink

    Usually you also want File.expand_path, to avoid multiple requires and such.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*