Reputation: 629
Here is my code
file_name = Dir['path/xml/test/*.txt']
file_name.to_s # => ["path/xml/test/test.txt"]
I want to return:
"test"
I can do it with the code below:
file_name = Dir['path/xml/test/*.txt']
file_name.to_s[15,60].gsub(/.txt["]/,"").gsub(/]/,"")
But it is not very elegant. Is there a more elegant way to just return the filename without .txt
and []
?
Upvotes: 0
Views: 84
Reputation: 168081
Yes.
File.basename(Dir['path/xml/test/*.txt'].first, ".txt")
# => "test"
To do it for all files,
Dir['path/xml/test/*.txt'].map{|e| File.basename(e, ".txt")}
Upvotes: 5
Reputation: 5290
Also possible in case there are more files ...
Dir[ 'path/name/*.txt' ].map { | e |
File.basename( e ).split(".").first
}
Upvotes: 0