0

I have

http://foobar.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg

How do I return

uploads/users/15/photos/12/foo.jpg
Christian Fazzini
  • 19,613
  • 21
  • 110
  • 215

5 Answers5

3

It is better to use the URI parsing that is part of the Ruby standard library than to experiment with some regular expression that may or may not take every possible special case into account.

require 'uri'

url = "http://foo.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg"

path = URI.parse(url).path  
# => "/uploads/users/15/photos/12/foo.jpg"

path[1..-1]
# => "uploads/users/15/photos/12/foo.jpg"

No need to reinvent the wheel.

Lars Haugseth
  • 14,721
  • 2
  • 45
  • 49
2
"http://foobar.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg".sub("http://foobar.s3.amazonaws.com/","")

would be an explicit version, in which you substitute the homepage-part with an empty string.

For a more universal approach I would recommend a regular expression, similar to this one:

string = "http://foobar.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg"
string.sub(/(http:\/\/)*.*?\.\w{2,3}\//,"")

If it's needed, I could explain the regular expression.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
robustus
  • 3,626
  • 1
  • 26
  • 24
  • btw. the sub on the string variable only returns the "uploads/users/15/photos/12/foo.jpg"-String, if you really want to change it, you would have to use .sub! – robustus Sep 12 '11 at 19:15
0

The cheap answer is to just strip everything before the first single /.

Better answers are "How do I process a URL in ruby to extract the component parts (scheme, username, password, host, etc)?" and "Remove subdomain from string in ruby".

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0
link = "http://foobar.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg"
path = link.match /\/\/[^\/]*\/(.*)/
path[1]
#=> "uploads/users/15/photos/12/foo.jpg"
fl00r
  • 82,987
  • 33
  • 217
  • 237
0

Someone recommended this approach as well:

URI.parse(URI.escape('http://foobar.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg')).path[1..-1]

Are there any disadvantages using something like this versus a regexp approach?

Christian Fazzini
  • 19,613
  • 21
  • 110
  • 215