LoginSignup
26
20

More than 5 years have passed since last update.

Ruby の Pathname に / メソッドがあればと思ったら既にあったという話

Last updated at Posted at 2015-04-14

Pathname とは

Ruby リファレンスマニュアル より引用:

パス名をオブジェクト指向らしく扱うクラスです。
Pathname オブジェクトはパス名を表しており、ファイルやディレクトリそのものを表してはいません。 当然、存在しないファイルのパス名も扱えます。絶対パスも相対パスも扱えます。

Pathname クラスを使えば

home = Pathname('/Users/foo')
home.join('Documents').to_path #=> "/Users/foo/Documents"

desktop = home.join 'Desktop'
desktop.join('hoge.txt').write('hogehoge')
destkop.join('hoge.txt').read #=> "hogehoge"

hoge_txt = desktop.join 'hoge.txt'
hoge_txt.to_s # => "/Users/foo/Desktop/hoge.txt"
hoge_txt.relative_path_from(home).to_s #=> "Desktop/hoge.txt"

のように割と辛いパスの扱いから解放してくれます。大変助かります。ちなみに Rails で

Rails.root.join('tmp').to_path #=> "/path/to/rails/tmp"

のように書けるのも、 Rails.root が Pathname を返すからですね。

本題

大変便利な Pathname ですが、

hoge_txt = home.join('Desktop').join('hoge.txt') # もしくは home.join('Desktop', 'hoge.txt')
hoge_txt.to_path #=> "/Users/foo/Desktop/hoge.txt"

パスを生成する場合、このようなコードを書くと思います。
こんなとき、 Pathname#/ メソッドがあったらいいんじゃないの、と思って調べてみたら普通にありました。

で、この Pathname#/ メソッドを使うと先ほどのコードが...

hoge_txt = home / 'Desktop' / 'hoge.txt'
hoge_txt.to_path #=> "/Users/foo/Desktop/hoge.txt"

こんな風に書けてしまいます。やばい。

ちなみに

この Pathname#/ メソッドは、Ruby 2.2 で入ったようです。Pathname#+ の別名ですね。 Pathname#+ もこの時初めて知りましたが。

Pathname はいろいろ捗るので、ドキュメントをきちんと読んでいろいろ試すと良いと思います。

26
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
20