Ruby-on-rails 在rails中将字符串转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35008941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:22:07 来源:igfitidea点击:
Convert string into Array in rails
提问by Ghulam Jilani
I send an array from rest client and received it like this: "[1,2,3,4,5]"
我从rest客户端发送一个数组并像这样接收它: "[1,2,3,4,5]"
Now I just want to convert it into Array without using Ruby's evalmethod. 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]
采纳答案by Ho Man
Perhaps this?
也许这个?
s.tr('[]', '').split(',').map(&:to_i)
回答by Cary Swoveland
require 'json'
JSON.parse "[1,2,3,4,5]"
#=> [1, 2, 3, 4, 5]
JSON.parse "[[1,2],3,4]"
#=> [[1, 2], 3, 4]
回答by shivam
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]

