How to split a delimited string in Ruby and convert it to an array?

前端 未结 5 1457
眼角桃花
眼角桃花 2020-12-12 10:18

I have a string

\"1,2,3,4\"

and I\'d like to convert it into an array:

[1,2,3,4]

How?

5条回答
  •  一个人的身影
    2020-12-12 10:32

    For String Integer without space as String

    arr = "12345"
    
    arr.split('')
    
    output: ["1","2","3","4","5"]
    

    For String Integer with space as String

    arr = "1 2 3 4 5"
    
    arr.split(' ')
    
    output: ["1","2","3","4","5"]
    

    For String Integer without space as Integer

    arr = "12345"
    
    arr.split('').map(&:to_i)
    
    output: [1,2,3,4,5]
    

    For String

    arr = "abc"
    
    arr.split('')
    
    output: ["a","b","c"]
    

    Explanation:

    1. arr -> string which you're going to perform any action.
    2. split() -> is an method, which split the input and store it as array.
    3. '' or ' ' or ',' -> is an value, which is needed to be removed from given string.

提交回复
热议问题