Best way to extract last segment of URI in Ruby

Daniel May picture Daniel May · Sep 10, 2012 · Viewed 18.3k times · Source

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?

Answer

Gumbo picture Gumbo · Sep 10, 2012

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