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

前端 未结 9 1824
日久生厌
日久生厌 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:18

    Sorry a bit late to the party and a bit surprised that nobody mentioned the drop method:

    ex="test1, test2, test3, test4, test5"
    ex.split(",").drop(1).join(",")
    => "test2,test3,test4,test5"
    
    0 讨论(0)
  • You can also do this:

    String is ex="test1, test2, test3, test4, test5"
    array = ex.split(/,/)
    array.size.times do |i|
      p array[i]
    end 
    
    0 讨论(0)
  • 2021-01-31 07:25

    Try split(",")[i] where i is the index in result array. split gives array below

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

    whose element can be accessed by index.

    0 讨论(0)
  • 2021-01-31 07:31

    if u want to use them as an array u already knew, else u can use every one of them as a different parameter ... try this :

    parameter1,parameter2,parameter3,parameter4,parameter5 = ex.split(",")
    
    0 讨论(0)
  • 2021-01-31 07:32
    ex="test1,test2,test3,test4,test5"
    all_but_first=ex.split(/,/)[1..-1]
    
    0 讨论(0)
  • 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"]
    
    0 讨论(0)
提交回复
热议问题