How to Get Filename Without Extension from File Path in Ruby

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.

Ruby extract filename from url without extension

You can use parse URL and then using File.basename

require 'uri'
url = "http://www.yahoo.com/14112753-dcfd-4d11-8191-8470a4ad6725.tgz"

uri = URI.parse(url)

File.basename(uri.path, ".tgz") # => "xy14112753-dcfd-4d11-8191-8470a4ad6725z"

if you want to get from any other extension just change .tgz to .*

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"

best way to remove file extension

Read the documentation of File::basename :

basename(file_name [, suffix] ) → base_name

Returns the last component of the filename given in file_name, which can be formed using both File::SEPARATOR and File::ALT_SEPARETOR as the separator when File::ALT_SEPARATOR is not nil. If suffix is given and present at the end of file_name, it is removed.

file = "/home/usr/my_file.xml"
File.basename(file,File.extname(file)) # => "my_file"

Finding a path without the file name

If File.absolute_path("test.txt") gives the absolute path, and you want the directory of it, then that means that you just want the current directory. That is given by:

Dir.pwd

How can I remove a filename extension from a string in Rails 4?

There are several ways, here are 2, with rpartition and a regex:

s = "more.name.stl"
puts s.sub(/\.[^.]+\z/, '') # => more.name
puts s.rpartition('.').first # => more.name

See the IDEONE demo

The rpartition way is clear, and as for the regex, it matches:

  • \. - a dot
  • [^.]+ - one or more characters other than a dot
  • \z - end of string.


Related Topics



Leave a reply



Submit