Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get components of a path as array

Tags:

ruby

I'd like to get the single components of a path as an array.

I came to these two solutions:

path = '/usr/share/doc/less/'

parts = path.split(File::Separator)
p parts #  => ["", "usr", "share", "doc", "less"]

require 'pathname'
parts = []
Pathname.new(path).each_filename {|f| parts << f}
p parts #  => ["usr", "share", "doc", "less"]
  1. String.split()

    Is this robust and portable?

  2. Pathname.each_filename()

    Looks a bit verbose for Ruby. However, this should be portable, right?

Are there better ways? Have I missed something that's standard Ruby?

like image 264
Scolytus Avatar asked Sep 14 '26 19:09

Scolytus


1 Answers

That's spot on. Pathname is part of ruby's standard library, and it should be an entirely portable solution.

You can just use this:

Pathname.new(path).each_filename.to_a

Or even:

Pathname(path).each_filename.to_a
like image 123
struthersneil Avatar answered Sep 16 '26 12:09

struthersneil