What is a good way to get the filename from a URL in Ruby? What is a good way to get the filename from a URL in Ruby? ruby ruby

What is a good way to get the filename from a URL in Ruby?


require 'uri'url = 'http://www.example.com/foo/bar/filename.jpg?2384973948743'uri = URI.parse(url)puts File.basename(uri.path)#=> filename.jpg


If you do not expect query_string in url, you can simply use File.basename

puts File.basename('http://example.com/folder1/folder2/file.txt')

This displays file.txt


The easiest way is probably to use URI.parse

url_object = URI.parse([my url])url_path = url_object.pathfilename = url_path.split("/").last