Jorge Cuevas Jorge Cuevas - 1 year ago 82
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:


I found that I can use the
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 Source

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

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

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download