Convert string into Array in rails

后端 未结 3 623
渐次进展
渐次进展 2020-12-10 03:01

I send an array from rest client and received it like this: \"[1,2,3,4,5]\"

Now I just want to convert it into Array without using Ruby\'s eval

相关标签:
3条回答
  • 2020-12-10 03:40

    Perhaps this?

       s.tr('[]', '').split(',').map(&:to_i)
    
    0 讨论(0)
  • 2020-12-10 03:47

    If you want to avoid eval, yet another way:

    "[1,2,3,4,5]".scan(/\d+/).map(&:to_i) #assuming you have integer Array as String
    #=> [1, 2, 3, 4, 5]
    
    0 讨论(0)
  • 2020-12-10 03:54
    require 'json'
    
    JSON.parse "[1,2,3,4,5]"
      #=> [1, 2, 3, 4, 5] 
    
    JSON.parse "[[1,2],3,4]"
      #=> [[1, 2], 3, 4] 
    
    0 讨论(0)
提交回复
热议问题