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

Viewed 24867

Short version -- How do I do Python rsplit() in ruby?

Longer version -- If I want to split a string into two parts (name, suffix) at the first '.' character, this does the job nicely:

name, suffix = name.split('.', 2)

But if I want to split at the last (rightmost) '.' character, I haven't been able to come up with anything more elegant than this:

idx = name.rindex('.')
name, suffix = name[0..idx-1], name[idx+1..-1] if idx

Note that the original name string may not have a dot at all, in which case name should be untouched and suffix should be nil; it may also have more than one dot, in which case only the bit after the final one should be the suffix.

6 Answers

You can also add rsplit to the String class by adding this at the top of your file.

class String
  def rsplit(pattern=nil, limit=nil)
    array = self.split(pattern)
    left = array[0...-limit].join(pattern)
    right_spits = array[-limit..]
    return [left] + right_spits
  end
end

It doesn't quite work like split. e.g.

$ pry
[1] pry(main)> s = "test.test.test"
=> "test.test.test"
[2] pry(main)> s.split('.', 1)
=> ["test.test.test"]
[3] pry(main)> s.split('.', 2)
=> ["test", "test.test"]
[4] pry(main)> s.split('.', 3)
=> ["test", "test", "test"]

vs.

[6] pry(main)> s
=> "test.test.test"
[7] pry(main)> s.rsplit('.', 1)
=> ["test.test", "test"]
[8] pry(main)> s.rsplit('.', 2)
=> ["test", "test", "test"]

But I can't quite work out how to short split it.

Related