How to split a string into only two parts, by the last occurrence of the split char?

For example:

"Angry Birds 2.4.1".split(" ", 2)
 => ["Angry", "Birds 2.4.1"] 

How can I split the string into: ["Angry Birds", "2.4.1"]


String#rpartition, e.g.

irb(main):068:0> str = "Angry Birds 2.4.1"
=> "Angry Birds 2.4.1"
irb(main):069:0> str.rpartition(' ')
=> ["Angry Birds", " ", "2.4.1"]

Since the returned value is an array, using .first and .last would allow to treat the result as if it was split in two, e.g

irb(main):073:0> str.rpartition(' ').first
=> "Angry Birds"
irb(main):074:0> str.rpartition(' ').last
=> "2.4.1"

I hava a solution like this:

class String
  def split_by_last(char=" ")
    pos = self.rindex(char)
    pos != nil ? [self[0...pos], self[pos+1..-1]] : [self]
  end
end

"Angry Birds 2.4.1".split_by_last  #=> ["Angry Birds", "2.4.1"]
"test".split_by_last               #=> ["test"]

Something like this maybe ? Split where a space is followed by anything but a space till the end of the string.

"Angry Birds 2.4.1".split(/ (?=\S+$)/)
#=> ["Angry Birds", "2.4.1"]

I don't seem able to get the example code in my comment properly formatted, so I'm submitting it as a separate answer, even though Vadym Tyemirov deserves all the credit for the String#rpartition solution he provided above.

I just wanted to add that String#rpartition plays very nicely with Ruby's "don't care" variable, as typically you're indeed only interested in the first and last element of the result array, but not the middle element (the separator):

[1] pry(main)> name, _, version = "Angry Birds 2.4.1".rpartition(' ')
=> ["Angry Birds", " ", "2.4.1"]
[2] pry(main)> name
=> "Angry Birds"
[3] pry(main)> version
=> "2.4.1"

So no need for Array#first or Array#last... less is more! :-)


"Angry Birds 2.4.1".split(/ (?=\d+)/)