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

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

    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! :-)

提交回复
热议问题