Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在rails中将字符串转换为数组_Ruby On Rails_Json_Ruby_Postman - Fatal编程技术网

Ruby on rails 在rails中将字符串转换为数组

Ruby on rails 在rails中将字符串转换为数组,ruby-on-rails,json,ruby,postman,Ruby On Rails,Json,Ruby,Postman,我从rest客户端发送了一个数组,并按如下方式接收:“[1,2,3,4,5]” 现在我只想将其转换为数组,而不使用Ruby的eval方法。我们可以使用Ruby的默认方法来实现这一点吗 "[1,2,3,4,5]" => [1,2,3,4,5] 也许是这个 s.tr('[]', '').split(',').map(&:to_i) 如果要避免eval,还有另一种方法: "[1,2,3,4,5]".scan(/\d+/).map(&:to_i) #assuming y

我从rest客户端发送了一个数组,并按如下方式接收:
“[1,2,3,4,5]”

现在我只想将其转换为数组,而不使用Ruby的
eval
方法。我们可以使用Ruby的默认方法来实现这一点吗

 "[1,2,3,4,5]" => [1,2,3,4,5]
也许是这个

   s.tr('[]', '').split(',').map(&:to_i)

如果要避免
eval
,还有另一种方法:

"[1,2,3,4,5]".scan(/\d+/).map(&:to_i) #assuming you have integer Array as String
#=> [1, 2, 3, 4, 5]

API是否使用JSON或YAML之类的特定格式?因为如果不是,考虑采用一个,那么您需要串行化格式。API使用JOSN。format@GhulamJilani您应该强烈考虑使用Ruby的JSON库,如下所示。注意:此方法有效地使多维数组扁平化。使用“<代码>”[“12”,“45”] 'Tr(']“,”).map(&:to_i)it返回错误:
未定义的方法map
tbh,此时,您应该只使用
JSON.parse
lol。但是如果您真的想要,
'[“12”,“45”]'.tr('[“]',”).split(“,”)
2警告:如果您希望它为非整数(如
'2.2'
或坏数据(如
'2sdf'
)引发
.map(&:to_i)
错误,则将其结尾处的
替换为
.map{x | Integer(x)}
(或
.map{x | Float(x)}
。使用此
'88,89100/.d扫描()
返回
[“8”、“8”、“8”、“9”、“1”、“0”、“0”]
@VishwasNahar将模式调整为
\d+
将解决此问题。我已更新了我的答案。谢谢:您绝对应该使用
JSON。parse
@vishwasnahart考虑到它的特性,这一个应该是可接受的答案votes@M.Habib同意其涵盖从“[1,2,3]”到“1,2,3]”的任何场景[“它包括”,“任何,场景”[“这个”,“太”]]
require 'json'

JSON.parse "[1,2,3,4,5]"
  #=> [1, 2, 3, 4, 5] 

JSON.parse "[[1,2],3,4]"
  #=> [[1, 2], 3, 4]