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

前端 未结 10 1440
猫巷女王i
猫巷女王i 2020-12-29 01:22

For example:

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

How can I split the string into: [\"Angry Bir

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 01:44

    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"]
    

提交回复
热议问题