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:
File.join(File.dirname(__FILE__), '..', '..', 'config', 'database.yml'))
Result:
[block:terminal]"./../../config/database.yml"[/block]
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?
File.join(File.dirname(__FILE__), %w[.. .. config database.yml]))
Result:
[block:terminal]"./../../config/database.yml"[/block]
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.
%w[.. .. config database.yml]
Result:
[block:terminal]["..", "..", "config", "database.yml"][/block]
But what if you have a space in the file name? Well you can use a backslash as an escape key and presto!
%w[.. .. config a\ file]
Result:
[block:terminal]["..", "..", "config", "a file"][/block]
[block:important]I'm not so sure what this operator is called, and any help giving it a name would be greatly appreciated.[/block]
