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

RubyUrlUri

Ruby 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionB SevenView Question on Stackoverflow
Solution 1 - Rubyuser904990View Answer on Stackoverflow
Solution 2 - RubyzainengineerView Answer on Stackoverflow
Solution 3 - RubyScott SView Answer on Stackoverflow