Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a stringified array back to array

I use hstore with Postgres 9.2 and Rails 3.2 to store my object like this:

class User
  user_hstore = {:user_id =>"123", :user_courses => [1,2,3]}
end

Now, when I retrieve user_courses, I get a string like this: '[1, 2, 3]'

How do I convert this string to Rails array? Better yet, is there a way to store an array within a hstore object so that Rails will automatically retrieve it as array type?

like image 832
AdamNYC Avatar asked Nov 30 '22 01:11

AdamNYC


2 Answers

JSON.parse "[\"1018\", \"1037\", \"1045\", \"1042\"]"
#=> ["1018", " 1037", " 1045", " 1042"]
like image 166
Lecky Lao Avatar answered Dec 19 '22 02:12

Lecky Lao


Why not just use eval?

eval('[1, 2, 3]')
#=> [1, 2, 3]

Obviously, don't do this on arbitrary or user inputted data, but on an array of integers as you've displayed, it's perfectly safe.

like image 24
Mike Avatar answered Dec 19 '22 04:12

Mike