Reputation: 13105
New to Ruby. I'm trying to figure out how to grab the name of a folder. I have this:
path = Dir["#{some_base_path}/*/*"]
Which gives me something like this:
path: ["/tmp/animals/cats/Fluffy"]
What I want is to know the name of the last subfolder - in this case Fluffy
.
I've tried variations of Pathname
and File.basename
, but I always run into no implicit conversion of Array into String (TypeError)
errors.
What would be the best way to do this?`
Upvotes: 0
Views: 197
Reputation: 2942
You already have your path. There is this neat thing in programming languages called Tokenization
You can split a string via a single character or more.
Starting with your array
paths = ["/tmp/animals/cats/Fluffy"]
=> ["/tmp/animals/cats/Fluffy"]
You could take the first element (which is your path string)
path = paths.first
=> "/tmp/animals/cats/Fluffy"
tokens = path.split("/")
=> ["", "tmp", "animals", "cats", "Fluffy"]
and then return the last element of the array of "tokens".
tokens.last
=> "Fluffy"
Upvotes: 2
Reputation: 15298
# Get array of subdirectories arrays
directories =
Dir[pattern].
filter_map { |filename| filename.split("/") if File.directory?(filename) }
# Get maximum subdirectories depth
max_depth = directories.max_by(&:size).size
# Get all subdirectories (tree leaves) with maximum depth
directories.filter_map { |dirs| dirs.last if dirs.size == max_depth }
Upvotes: 0