Blankman
Blankman

Reputation: 266960

How to get the file extension from a url?

New to ruby, how would I get the file extension from a url like:

http://www.example.com/asdf123.gif

Also, how would I format this string, in c# I would do:

string.format("http://www.example.com/{0}.{1}", filename, extension);

Upvotes: 39

Views: 22907

Answers (5)

MothOnMars
MothOnMars

Reputation: 2369

I realize this is an ancient question, but here's another vote for using Addressable. You can use the .extname method, which works as desired even with a query string:

 Addressable::URI.parse('http://www.example.com/asdf123.gif').extname # => ".gif"
 Addressable::URI.parse('http://www.example.com/asdf123.gif?foo').extname # => ".gif"

Upvotes: 3

Orlando
Orlando

Reputation: 9692

This works for files with query string

file = 'http://recyclewearfashion.com/stylesheets/page_css/page_css_4f308c6b1c83bb62e600001d.css?1343074150'
File.extname(URI.parse(file).path) # => '.css'

also returns "" if file has no extension

Upvotes: 33

AdrianoKF
AdrianoKF

Reputation: 3021

You could use Ruby's URI class like this to get the fragment of the URI (i.e. the relative path of the file) and split it at the last occurrence of a dot (this will also work if the URL contains a query part):

require 'uri'
your_url = 'http://www.example.com/asdf123.gif'
fragment = URI.split(your_url)[5]

extension = fragment.match(/\.([\w+-]+)$/)

Upvotes: 2

Rafe Kettler
Rafe Kettler

Reputation: 76955

url = 'http://www.example.com/asdf123.gif'
extension = url.split('.').last

Will get you the extension for a URL(in the most simple manner possible). Now, for output formatting:

printf "http://www.example.com/%s.%s", filename, extension

Upvotes: 7

Simone Carletti
Simone Carletti

Reputation: 176372

Use File.extname

File.extname("test.rb")         #=> ".rb"
File.extname("a/b/d/test.rb")   #=> ".rb"
File.extname("test")            #=> ""
File.extname(".profile")        #=> ""

To format the string

"http://www.example.com/%s.%s" % [filename, extension]

Upvotes: 70

Related Questions