I send an array from rest client and received it like this: "[1,2,3,4,5]"
我从休息客户端发送一个数组并收到它:“[1,2,3,4,5]”
Now I just want to convert it into Array without using Ruby's eval
method. Any Ruby's default method that we could use for this?
现在我只想将它转换为Array而不使用Ruby的eval方法。我们可以使用任何Ruby的默认方法吗?
"[1,2,3,4,5]" => [1,2,3,4,5]
3 个解决方案
#1
4
Perhaps this?
也许这个?
s.tr('[]', '').split(',').map(&:to_i)
#2
25
require 'json'
JSON.parse "[1,2,3,4,5]"
#=> [1, 2, 3, 4, 5]
JSON.parse "[[1,2],3,4]"
#=> [[1, 2], 3, 4]
#3
3
If you want to avoid eval
, yet another way:
如果你想避免使用eval,还有另一种方法:
"[1,2,3,4,5]".scan(/\d/).map(&:to_i) #assuming you have integer Array as String
#=> [1, 2, 3, 4, 5]
#1
4
Perhaps this?
也许这个?
s.tr('[]', '').split(',').map(&:to_i)
#2
25
require 'json'
JSON.parse "[1,2,3,4,5]"
#=> [1, 2, 3, 4, 5]
JSON.parse "[[1,2],3,4]"
#=> [[1, 2], 3, 4]
#3
3
If you want to avoid eval
, yet another way:
如果你想避免使用eval,还有另一种方法:
"[1,2,3,4,5]".scan(/\d/).map(&:to_i) #assuming you have integer Array as String
#=> [1, 2, 3, 4, 5]