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

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

    The rpartition solution makes a great sexy one-liner (I voted for it), but here's another technique if you want a one liner that's more flexible for solving more complex partitioning problems:

    ["Angry Birds 2.4.1".split(' ')[0..-2].join(' '), "Angry Birds 2.4.1".split(' ')[-1..-1].join(' ')]
    

    By more flexible, I mean if there were more items being partitioned, you could just adjust the range of the sequence.

提交回复
热议问题