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?
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"
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With