Paths aren't strings – Roblog, the blog of Rob Miller

submited by
Style Pass
2021-05-25 02:00:08

In Ruby, we deal often with files; reading them, writing them, checking whether or not they exist. When working with these files, we generally reference them by their paths on the filesystem: /etc/hosts, for example, or /usr/local/bin/git.

As in other languages, it’s pretty common in Ruby to represent these filesystem paths as strings. In a way, that’s fine: it works okay, and if we want to do something that gets to the files that they represent, there are methods on File that can help us find what we want (for fetching the absolute path of a relative filename, or checking whether a file exists, for example).

But in the world of Ruby, with its rich object model, this feels neither very idiomatic nor very object oriented. There’s lots of behaviour associated with paths, and strings don’t encapsulate this behaviour very well.

Paths can be relative, for example. That is, multiple paths that seem different when expressed as a string can in fact correspond to the same file; if we’re in the /usr/local directory, for example, we can reach /etc/hosts using the paths /etc/hosts or ../../etc/hosts; we can reach /usr/local/bin/git with both /usr/local/bin/git and bin/git. To check if one string path is the same as the other, then, we can’t just do path1 == path2.

Leave a Comment