[Ruby] Ruby で URL や Path 文字列を分割する

小ネタ。

[markdown]

> * [linux – How to split a directory string in Ruby? – Stack Overflow](https://stackoverflow.com/questions/1370988/how-to-split-a-directory-string-in-ruby/21572944#21572944)

`File::SEPARATOR` という定数があるんですね。

> ファイルパスのセパレータです。ファイルを扱うメソッドにパス名を渡す場合などスクリプト内のパス名は環境によらずこのセパレータで統一され ます。値は “/” です。
>
> [constant File::SEPARATOR (Ruby 2.5.0)](https://docs.ruby-lang.org/ja/latest/method/File/c/SEPARATOR.html)

“`ruby
% pry
[1] pry(main)> item = ‘https://www.d-wood.com/blog/category/ruby’
=> “https://www.d-wood.com/blog/category/ruby”
[2] pry(main)> item.split(File::SEPARATOR)
=> [“https:”, “”, “www.d-wood.com”, “blog”, “category”, “ruby”]
“`

`pathname` 扱いやすい。

> * [Class: Pathname (Ruby 2.5.0)](http://ruby-doc.org/stdlib-2.5.0/libdoc/pathname/rdoc/Pathname.html)

“`ruby
[3] pry(main)> Pathname(item).each_filename.to_a
=> [“https:”, “www.d-wood.com”, “blog”, “category”, “ruby”]
“`

[/markdown]