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?
A JSON parser ought to work fine:
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
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:
require 'yaml'
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
YAML.load(str) #=> [[591, 184], [741, 910], [987, 512], [2974, 174]]
[\d,?\s?]+. In a character class question marks are taken literally, so this will match one or more digits, commas, question marks, or whitespace characters.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]]"]
You have to use "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]]
eval is an absolute last resort. Since this data is valid JSON, Jordan has a better idea.