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
I Want to Return a Single Result Using .Find() with Ruby on Rails
How to Sort a Ruby Array by Two Conditions
Does Ruby Provide a Constant_Added Hook Method
Why Rails Instance Method Can Be Used as Class Method in Rspec
Duplicate Elements of Array in Ruby
Error Loading the 'Sqlite3' Active Record Adapter. When I Deploy in Heroku
How to Condense Summable Metrics to a Unique Identifier in a Ruby Table
How to Use 'Debugger' and 'Pry' When Developing a Gem? (Ruby)
Selenium Webdriver Take Screenshot of Viewport Only
How to Fix My Cucumber Expectation Error When Polling
Ruby Roo Loaderror: Cannot Load Such File -- Spreadsheet/Note
Access Image from Different View in a View with Paperclip Gem Ruby on Rails
Knowing When Resque Worker Had Completed Job
Rails Undefined Method 'Errors' for Nil:Nilclass in Simple_Form