I have a string representation of array:
val1 = "[[\":one\", \":two\"], [\":four\", \":one\"]]"
What is the best way to convert it into:
val2 = [[:one,:two], [:four, :one]]
The dimension of array could be 25 x 25.
Use JSON.parse:
require 'json'
val2 = JSON.parse val1
# => [[":one", ":two"], [":four", ":one"]]
or you can convert them to symbols like this:
val2.map{|a,b| [a.sub(/^:/,'').to_sym, b.sub(/^:/,'').to_sym]}
# => [[:one, :two], [:four, :one]]
sym JSON.parse(val1.tr(':','')) #=> [[:one, :two], [:four, :one]], where def sym(arr); arr.each_with_object([]) { |e,a| a << (e.is_a?(Array) ? sym(e) : e.to_sym) }; end. Suppose val1 has another layer of nesting: val1 = "[[\":one\", [\":two\", \":three\"]], [\":four\", \":one\"]]". Then sym JSON.parse(val1.tr(':','')) #=> [[:one, [:two, :three]], [:four, :one]].You can use YAML.load:
require 'yaml'
YAML.load(val1.delete ':').map{|x| x.map(&:to_sym)}
# => [[:one, :two], [:four, :one]]
And I guess I should be ready for downvotes, but you can use eval:
eval(val1).map{|x| x.map(&method(:eval))}
# => [[:one, :two], [:four, :one]]
eval :D