What is a good way to get the filename from a URL in Ruby?
RubyUrlUriRuby Problem Overview
What is a good way to extract filename.jpg
from:
url = 'http://www.example.com/foo/bar/filename.jpg?2384973948743'
I'm using Ruby 1.9.3.
Ruby Solutions
Solution 1 - Ruby
require 'uri'
url = 'http://www.example.com/foo/bar/filename.jpg?2384973948743'
uri = URI.parse(url)
puts File.basename(uri.path)
#=> filename.jpg
Solution 2 - Ruby
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
Solution 3 - Ruby
The easiest way is probably to use URI.parse
url_object = URI.parse([my url])
url_path = url_object.path
filename = url_path.split("/").last