saigkill saigkill - 6 months ago 13
Ruby Question

Get file name and extension in Ruby

I'm working on a program to download a video from YouTube, convert it to MP3 and create a directory structure for the files.

My code is:

FileUtils.cd("#{$musicdir}/#{$folder}") do
YoutubeDlhelperLibs::Downloader.get($url)
if File.exists?('*.mp4')
puts 'Remove unneeded tempfile'
Dir['*.mp4'].each do |waste|
File.delete(waste)
end
else
puts 'Temporary file already deleted'
end

Dir['*.m4a'].each do |rip|
rip.to_s
rip.split
puts 'Inside the function'
puts rip
end

end


The first one goes to the already created music folder. Inside that I'm executing
get
. After that I have two files in the directory: "xyz.mp4" and "xyz.m4a".

I would like to fetch the filename without the extension so I can handle both files differently.

I'm using an array, but an array for just one match sounds crazy for me.

Has anyone another idea?

Answer

You can use the following functions for your purpose:

file = "/path/to/xyz.mp4"

comp = File.basename file        # => "xyz.mp4"
extn = File.extname  file        # => ".mp4"
name = File.basename file, extn  # => "xyz"
path = File.dirname  file        # => "/path/to"