0

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?

0

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

Comments

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:

require 'yaml'
str = "[[591, 184] , [741, 910] , [987,512], [2974, 174]]"
YAML.load(str) #=> [[591, 184], [741, 910], [987, 512], [2974, 174]]

1 Comment

I'm confused about the character class [\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.
2

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]]"]  

Comments

0

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]] 

1 Comment

Although technically true, eval is an absolute last resort. Since this data is valid JSON, Jordan has a better idea.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.