user1735921 user1735921 - 6 months ago 10
Ruby Question

Converting array/hash to string and converting that string back to array/hash in ruby

I had this array lets say,

array = [{'key' => 0},1]


so now
array[0]['key']
has value
0
.
When I convert it to string like this:

array.to_s


Now the array is not an array its a string which is like this:

"[{'key' => 0},1]"


If I do
array[0]
now, it will output
[


I want to convert this back to array so that I can use
array[0]['key']
again.

Full Code:

array = [{'key' => 0},1]
array = array.to_s
puts array[0]['key'] #Should output 0 but it does not output anything


The thing is that I have already saved stuff like that in the database, so now I need to use that stuff back, so the only way is to parse the saved string (which was actually an array).

Answer
string = "[{'key' => 0},1]"
array = eval string
array[0]['key']  # => 0