How to split a string in Ruby and get all items except the first one?

前端 未结 9 1839
日久生厌
日久生厌 2021-01-31 06:47

String is ex=\"test1, test2, test3, test4, test5\"

when I use

ex.split(\",\").first

it returns

\"test1\"
         


        
9条回答
  •  有刺的猬
    2021-01-31 07:37

    ex.split(',', 2).last
    

    The 2 at the end says: split into 2 pieces, not more.

    normally split will cut the value into as many pieces as it can, using a second value you can limit how many pieces you will get. Using ex.split(',', 2) will give you:

    ["test1", "test2, test3, test4, test5"]
    

    as an array, instead of:

    ["test1", "test2", "test3", "test4", "test5"]
    

提交回复
热议问题