1

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.

5 Answers 5

8

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]]
Sign up to request clarification or add additional context in comments.

2 Comments

Note that that does not give exactly what the OP wants, although there may be possibility is that the OP is sloppy, and has asked not what they wanted.
Consider 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]].
4

You can use YAML.load:

require 'yaml'    
YAML.load(val1.delete ':').map{|x| x.map(&:to_sym)}
# => [[:one, :two], [:four, :one]]

Demonstration

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

Demonstration

6 Comments

What if the string is too long. Will it slow down the performance?
@Def: I don't think it really will be that noticeably.
Let me know if you need help fighting off the angry mob.
I guess the mob is quite content with eval :D
Just a side question for @Def: How did you get this kind of array representation? Maybe you should try using CSV or JSON (or other known format) instead of trying to concoct your own parser?
|
2
eval val1.tr('"','') #=> [[:one, :two], [:four, :one]]

Comments

0
eval val1.gsub '"',''   #=> [[:one,:two], [:four, :one]]

Comments

0

val1 = "[[\":one\", \":two\"], [\":four\", \":one\"]]" puts val1.unpack('ZZ')

Descrition: 'unpack' decodes the string (which may contain binary data). According to the format string, it is returning an array of each value extracted. In the above code, Z stands for null terminated string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.