For example:
\"Angry Birds 2.4.1\".split(\" \", 2)
=> [\"Angry\", \"Birds 2.4.1\"]
How can I split the string into: [\"Angry Bir
String#split_on_last method.Heavily inspired by halfelf's answer but permits more than just a single character, doesn't have a default param value and refactored for clarity.
Class String
def split_on_last( text )
position_of_last_occurrence = self.rindex( text )
return self if position_of_last_occurrence.nil?
first_part = self[ 0...position_of_last_occurrence ]
last_part = self[ position_of_last_occurrence + text.length..-1 ]
[ first_part, last_part ]
end
end
"Angry Birds 2.4.1".split_on_last( " " )
#=> ["Angry Birds", "2.4.1"]
"start middle end end suffix".split_on_last( "end" )
=> ["start middle end ", " suffix"]