Ruby: Split string at character, counting from the right side

String#rpartition does just that:

name, match, suffix = name.rpartition('.')

It was introduced in Ruby 1.8.7, so if running an earlier version you can use require 'backports/1.8.7/string/rpartition' for that to work.


Put on the thinking cap for a while and came up with this regexp:

"what.to.do.now".split(/\.([^.]*)$/)
=> ["what.to.do", "now"]

Or in human terms "split at dot, not followed by another dot, at end of string". Works nicely also with dotless strings and sequences of dots:

"whattodonow".split(/\.([^.]*)$/)
=> ["whattodonow"]
"what.to.do...now".split(/\.([^.]*)$/)
=> ["what.to.do..", "now"]

Here's what I'd actually do:

/(.*)\.(.*)/.match("what.to.do")[1..2]
=> ["what.to", "do"]

or perhaps more conventionally,

s = "what.to.do"

s.match(/(.*)\.(.*)/)[1..2]
=> ["what.to", "do"]

Tags:

String

Ruby

Split