简体   繁体   中英

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM