Best way to extract last segment of URI in Ruby

社会主义新天地 提交于 2019-12-03 05:00:26

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
saihgala
uri.split('/')[-1] 

or

uri.split('/').last 

Try these:

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

Or

last = File.basename(url)

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:pass@example.com/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.

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)

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!