randombits
randombits

Reputation: 48460

Convert ruby array to string and vice versa

I'm currently storing an array using its string representation in a MySQL TEXT column. This works for the application I'm building just great when I'm retrieving data. The problem is, I need to convert this string at some point and using String#to_a just stuffs the array as a string in a one element array. Here's an example:

:026 > my_arr = [["foo", 1], ["bar", 2]]
 => [["foo", 1], ["bar", 2]] 
:027 > my_str = my_arr.inspect
 => "[[\"foo\", 1], [\"bar\", 2]]" 

so far so good.

The conversion back however, won't work for obvious reasons:

:029 > my_str.to_a
 => ["[[\"foo\", 1], [\"bar\", 2]]"]

What's the right way of going about this?

NOTE

I do not want to use eval. It does exactly what I need in this case, but I can't trust the input as this array is provided by the user.

Upvotes: 0

Views: 669

Answers (1)

Andy Waite
Andy Waite

Reputation: 11076

Serialize it as JSON or YAML or something.

Upvotes: 1

Related Questions