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

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

    You probably mistyped a few things. From what I gather, you start with a string such as:

    string = "test1, test2, test3, test4, test5"
    

    Then you want to split it to keep only the significant substrings:

    array = string.split(/, /)
    

    And in the end you only need all the elements excluding the first one:

    # We extract and remove the first element from array
    first_element = array.shift
    
    # Now array contains the expected result, you can check it with
    puts array.inspect
    

    Did that answer your question ?

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

    Since you've got an array, what you really want is Array#slice, not split.

    rest = ex.slice(1 .. -1)
    # or
    rest = ex[1 .. -1]
    
    0 讨论(0)
  • 2021-01-31 07:42

    Try this:

    first, *rest = ex.split(/, /)
    

    Now first will be the first value, rest will be the rest of the array.

    0 讨论(0)
提交回复
热议问题