Get File Name and Extension in Ruby

Find the extension of a filename in Ruby

irb(main):002:0> accepted_formats = [".txt", ".pdf"]
=> [".txt", ".pdf"]
irb(main):003:0> File.extname("example.pdf") # get the extension
=> ".pdf"
irb(main):004:0> accepted_formats.include? File.extname("example.pdf")
=> true
irb(main):005:0> accepted_formats.include? File.extname("example.txt")
=> true
irb(main):006:0> accepted_formats.include? File.extname("example.png")
=> false

Get file name and extension in 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"

Ruby: Get filename without the extensions

Thanks to @xdazz and @Monk_Code for their ideas. In case others are looking, the final code I'm using is:

File.basename(__FILE__, ".*").split('.')[0]

This generically allows you to remove the full path in the front and the extensions in the back of the file, giving only the name of the file without any dots or slashes.

How to get filename without extension from file path in Ruby

require 'pathname'

Pathname.new('/opt/local/bin/ruby').basename
# => #<Pathname:ruby>

I haven't been a Windows user in a long time, but the Pathname rdoc says it has no issues with directory-name separators on Windows.

how to get file name and extension from directory

Dir.glob("*")
# => ["test.rb", "a.txt", ..... ]
# or find all files recursively
Dir.glob("./**/*")

How to get the file extension from a url?

Use File.extname

File.extname("test.rb")         #=> ".rb"
File.extname("a/b/d/test.rb") #=> ".rb"
File.extname("test") #=> ""
File.extname(".profile") #=> ""

To format the string

"http://www.example.com/%s.%s" % [filename, extension]

Changing file extension using ruby

Improving the previous answer a little:

require 'fileutils'
Dir.glob('/path_to_file_directory/*.eml').each do |f|
FileUtils.mv f, "#{File.dirname(f)}/#{File.basename(f,'.*')}.html"
end

The File.basename(f,'.*') will give you the name without the extension otherwise the files will endup being file_name.eml.html instead of file_name.html



Related Topics



Leave a reply



Submit