简体   繁体   中英

Get components of a path as array

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM