Get file name and extension in Ruby

RubyFile

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

You can use the following functions for your purpose:

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

File.basename(path)         # => "xyz.mp4"
File.extname(path)          # => ".mp4"
File.basename(path, ".mp4") # => "xyz"
File.basename(path, ".*")   # => "xyz"
File.dirname(path)          # => "/path/to"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSascha MannsView Question on Stackoverflow
Solution 1 - RubyStoicView Answer on Stackoverflow