I want to find File extensions like .gif,.jpg,.txt from the uri like http://testasp.vulnweb.com/avatars/noavatar.gif.
Asked
Active
Viewed 9,789 times
4 Answers
25
You can use an extname method of File
url = "http://testasp.vulnweb.com/avatars/noavatar.gif"
File.extname(url) #=> .gif

alony
- 10,725
- 3
- 39
- 46
-
You're assuming that the URL looks like a file path but that's not necessarily a valid assumption. What happens if there's a fragment or CGI parameters? – mu is too short Nov 18 '16 at 19:56
5
There may be an easier way to do this but I'd recommend using a combination of the Pathname
and URI
libraries
require 'uri'
uri = URI("http://testasp.vulnweb.com/avatars/noavatar.gif")
path = uri.path # /avatars/noavatar.gif
pathname = Pathname.new(path)
extension = pathname.extname # gif

Chris Bailey
- 4,126
- 24
- 28
-
Thanx for your replay...my another question is how can i traverse through the source folder of a uri and get extensions?... – Nidhi Barot Jan 06 '12 at 11:56
2
If you are in Rails and you are talking about the request URL path's extension you can do this from a controller or helper:
File.extname(request.path)
Noting that request.path is a method of the request object in the rails controller.
And noting that request.path will never return nil.

Mike P.
- 198
- 1
- 12
0
I know that you asked about extracting file extension, though take a look at this question/answers Determine file type in Ruby it's better and more secure to rely on mime type rather than extension.