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"
.
You need to use "\n" not '\n' in your gsub.
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.
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 .
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.
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"
Use the right tool for the job:
require 'uri' url = "https://www.facebook.com/hackerbob" URI.parse(url).path[1..-1] # => "hackerbob"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With