Ruby: Get filename without the extensions
How can I get the filename without the extensions? For example, input of "/dir1/dir2/test.html.erb"
should return "test"
.
In actual code I will passing in __FILE__
instead of "/dir1/dir2/test.html.erb"
.
Solution 1:
Read documentation:
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_SEPARATOR 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.basename('public/500.html', '.html')
=> "500"
in you case:
=> File.basename("test.html.erb", ".html.erb")
=> "test"
Solution 2:
How about this
File.basename(f, File.extname(f))
returns the file name without the extension.. works for filenames with multiple '.' in it.