Jorge Cuevas Jorge Cuevas - 4 months ago 17
Ruby Question

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?

Answer

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.