Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to remove the extension from a string with the following structure:

name.stl

I found that I can use the basename method to get the string. The problem is that I am not using the file path, and I already have the string with the name. I just need to delete the extension from the string.

It seems to me that a regular expression would be a great option to detect the dot and delete everything from it to the end.

How can I use a regex to do this on Ruby on Rails 4?

like image 997
Jorge Cuevas Avatar asked Dec 15 '22 05:12

Jorge Cuevas


2 Answers

Just use the built-in methods. These will work correctly across different OSes:

filename = '/path/to/foo.bar'
File.basename(filename) # => "foo.bar"
File.extname(filename) # => ".bar"
File.basename(filename, File.extname(filename)) # => "foo"

And, in case you need the containing directory:

File.dirname(filename) # => "/path/to"

If you don't care, then a simple split('.') would work:

'foo.bar'.split('.').first # => "foo"

or

'foo.bar'[/^[^.]+/] # => "foo"
like image 79
the Tin Man Avatar answered May 10 '23 14:05

the Tin Man


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.
like image 28
Wiktor Stribiżew Avatar answered May 10 '23 16:05

Wiktor Stribiżew