Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to extract last segment of URI in Ruby

Given URI strings like:

http://www.somesite.com/abc
http://www.somesite.com/alpha/beta/abc
http://www.somesite.com/alpha/abc

What's the most elegant way in Ruby to grab the abc at the end of these URIs?

like image 856
Daniel May Avatar asked Sep 10 '12 05:09

Daniel May


4 Answers

I would use a proper URI parser like the one of the URI module to get the path from the URI. Then split it at / and get the last part of it:

require 'uri'

URI(uri).path.split('/').last
like image 129
Gumbo Avatar answered Nov 14 '22 20:11

Gumbo


uri.split('/')[-1] 

or

uri.split('/').last 
like image 34
saihgala Avatar answered Nov 14 '22 20:11

saihgala


While all the usages of split suggested in the answers here are legit, in my opinion @matsko's answer is the one with the clearer code to read:

last = File.basename(url)
like image 6
mokagio Avatar answered Nov 14 '22 19:11

mokagio


Try these:

if url =~ /\/(.+?)$/
  last = $1
end

Or

last = File.basename(url)
like image 4
matsko Avatar answered Nov 14 '22 20:11

matsko