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

前端 未结 10 1469
猫巷女王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:39

    Create a 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.

    Definition

    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
    

    Usage

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

提交回复
热议问题