Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

url

uri

ruby

People also ask

What does __ FILE __ mean in Ruby?

The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.


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.path
filename = url_path.split("/").last