0

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

1

1 Answer 1

3
string = "[{'key' => 0},1]"
array = eval string
array[0]['key']  # => 0
Sign up to request clarification or add additional context in comments.

4 Comments

using eval in this case is a bad practice.
I see, thank you for the warning, could you elaborate more please?
You can read this question
@Ilya well I just need to correct my database so I guess its fine. I am not using this on permanent basis.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.