Best way to extract last segment of URI in Ruby
Asked Answered
H

6

26

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?

Hocus answered 10/9, 2012 at 5:4 Comment(3)
@oldergod: http://example.com/where?is=pancakes/house%3F.Augustineaugustinian
@muistooshort how would you do it? taking everything from the last / before the first ??Chiquita
@oldergod: yeah, see Gumbo's answer.Augustineaugustinian
E
61

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
Electrosurgery answered 10/9, 2012 at 5:13 Comment(2)
@Chiquita So what do you get instead?Electrosurgery
@muistooshort You can use path.chomp('/') to remove them before splitting.Electrosurgery
B
15
uri.split('/')[-1] 

or

uri.split('/').last 
Barahona answered 10/9, 2012 at 5:10 Comment(0)
A
7

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)
Albertinealbertite answered 25/3, 2018 at 20:16 Comment(0)
V
4

Try these:

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

Or

last = File.basename(url)
Veranda answered 10/9, 2012 at 5:11 Comment(0)
A
2

From the Terminal command line:

ruby -ruri -e "print File.basename(URI.parse('$URI').path)"

from inside your .rb source:

require 'uri'
theURI = 'http://user:[email protected]/foo/bar/baz/?lala=foo'
uriPathTail = File.basename(URI.parse(theURI).path) # => baz

it works well with whatever legal theURI you had.

If you don't use URI.parse(), any parameter to the url will be wrongly taken as the last segment of the URI.

Akilahakili answered 27/5, 2015 at 8:33 Comment(0)
V
2

If the value is any orbitary string + URI, then the below solution should work.

First, extract URI from the string:

uri_string = URI.extract("Test 123 http://www.somesite.com/abc")

Above command returns an array

Then extract the last part of the URI using

uri_string[0].split('/').last

prerequisite: require "uri" needs to be added to the ruby script

Victualler answered 2/5, 2019 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.