Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you return everything after last slash(/) in a Ruby string [closed]

I have a string would like everything after the last / to be returned.

E.g. for https://www.example.org/hackerbob, it should return "hackerbob".

like image 223
Hendrik Avatar asked Jun 18 '12 11:06

Hendrik


People also ask

How do you get rid of the N at the end of a string in Ruby?

You need to use "\n" not '\n' in your gsub.

How do you change the last character of a string in Ruby?

The chop method is used to remove the last character of a string in Ruby. If the string ends with \r\n , it will remove both the separators. If an empty string calls this method, then an empty string is returned. We can call the chop method on a string twice.

What does \n do in Ruby?

In double quoted strings, you can write escape sequences and Ruby will output their translated meaning. A \n becomes a newline. In single quoted strings however, escape sequences are escaped and return their literal definition. A \n remains a \n .

How to access index of string in Ruby?

The string. index() method is used to get the index of any character in a string in Ruby. This method returns the first integer of the first occurrence of the given character or substring.


2 Answers

I don't think a regex is a good idea, seeing how simple the task is:

irb(main):001:0> s = 'https://www.facebook.com/hackerbob' => "https://www.facebook.com/hackerbob" irb(main):002:0> s.split('/')[-1] => "hackerbob" 

Of course you could also do it using regex, but it's a lot less readable:

irb(main):003:0> s[/([^\/]+)$/] => "hackerbob" 
like image 181
Niklas B. Avatar answered Oct 08 '22 20:10

Niklas B.


Use the right tool for the job:

require 'uri' url = "https://www.facebook.com/hackerbob" URI.parse(url).path[1..-1]  # => "hackerbob" 
like image 31
Lars Haugseth Avatar answered Oct 08 '22 19:10

Lars Haugseth