Home > other >  Ruby - array inside quotes
Ruby - array inside quotes

Time:02-15

In Ruby / Ruby On Rails, I have a string containing an array literal:

"[523, 456]"

How do I convert this string to array

[523, 456]

CodePudding user response:

That's a valid JSON

JSON.parse("[523, 456]")
=> [523, 456]

if you're in plain ruby don't forget to

require 'json'

CodePudding user response:

Here's a pure Ruby approach that should work for your particular use case, assuming all array elements are integers:

"[523, 456]"[1..-2].split(", ").map(&:to_i)
  • Related