This question already has an answer here:
这个问题在这里已有答案:
- Convert string into Array in rails 3 answers
- 在rails 3答案中将字符串转换为数组
I am having string:
我有字符串:
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
I want to convert this to an array:
我想将其转换为数组:
arr = [[591, 184] , [741, 910] , [987,512], [2974, 174]]
How can i do this?
我怎样才能做到这一点?
4 个解决方案
#1
6
A JSON parser ought to work fine:
JSON解析器应该正常工作:
require "json"
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
p JSON.parse(str)
# => [[591, 184], [741, 910], [987,512], [2974, 174]]
Try it on eval.in: https://eval.in/777054
在eval.in上试试:https://eval.in/777054
#2
2
One way to do this:
一种方法:
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
reg = /(?<=\[)[\d,?\s?]+(?=\])/
str.scan(reg).map { |s| s.scan(/\d+/).map(&:to_i) }
#=> [[591, 184], [741, 910], [987, 512], [2974, 174]]
or taking a leaf out of @Jordan's book, but using YAML:
或者从@Jordan的书中拿出一片叶子,但是使用YAML:
require 'yaml'
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
YAML.load(str) #=> [[591, 184], [741, 910], [987, 512], [2974, 174]]
#3
1
I would split
and scan
in two steps.
我会分两步拆分和扫描。
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
str.split(/\]\s*,\s*\[/).map { |s| s.scan(/\d+/).map(&:to_i) }
#=> [[591, 184], [741, 910], [987, 512], [2974, 174]]
Note that
注意
str.split(/\]\s*,\s*\[/)
# => ["[[591, 184", "741, 910", "987,512", "2974, 174]]"]
#4
0
You have to use "eval":
你必须使用“eval”:
> str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
# => "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
> arr = eval str
# => [[591, 184], [741, 910], [987, 512], [2974, 174]]
#1
6
A JSON parser ought to work fine:
JSON解析器应该正常工作:
require "json"
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
p JSON.parse(str)
# => [[591, 184], [741, 910], [987,512], [2974, 174]]
Try it on eval.in: https://eval.in/777054
在eval.in上试试:https://eval.in/777054
#2
2
One way to do this:
一种方法:
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
reg = /(?<=\[)[\d,?\s?]+(?=\])/
str.scan(reg).map { |s| s.scan(/\d+/).map(&:to_i) }
#=> [[591, 184], [741, 910], [987, 512], [2974, 174]]
or taking a leaf out of @Jordan's book, but using YAML:
或者从@Jordan的书中拿出一片叶子,但是使用YAML:
require 'yaml'
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
YAML.load(str) #=> [[591, 184], [741, 910], [987, 512], [2974, 174]]
#3
1
I would split
and scan
in two steps.
我会分两步拆分和扫描。
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
str.split(/\]\s*,\s*\[/).map { |s| s.scan(/\d+/).map(&:to_i) }
#=> [[591, 184], [741, 910], [987, 512], [2974, 174]]
Note that
注意
str.split(/\]\s*,\s*\[/)
# => ["[[591, 184", "741, 910", "987,512", "2974, 174]]"]
#4
0
You have to use "eval":
你必须使用“eval”:
> str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
# => "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
> arr = eval str
# => [[591, 184], [741, 910], [987, 512], [2974, 174]]