Convert a stringified array back to array

耗尽温柔 提交于 2019-12-07 09:03:14

问题


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?


回答1:


JSON.parse "[\"1018\", \"1037\", \"1045\", \"1042\"]"
#=> ["1018", " 1037", " 1045", " 1042"]



回答2:


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.




回答3:


To convert it to an array:

user_courses.gsub('[', '').gsub(']', '').split(",")

To make retrieval simpler, you can store it as a string by doing

user_hstore = {:user_id =>"123", :user_courses => '1,2,3'}



回答4:


Just to throw another hat into the ring, this accomplishes the same as Vimsha's answer but is a little more short and sweet you could do:

"[1,2,3,4]"[1..-2].split(",")

which in your case could be:

user_courses[1..-2].split(",")

Edit: If speed is a concern I did a quick benchmark which can be found here. Doing only a few items is not a very big difference but 10,000 items + you can start seeing a difference. This is at 100,000 items:

  # "[1,2,3,4]"[1..-2].split(",")
  0.110000   0.000000   0.110000 (  0.114739)

  # "[1,2,3,4]".gsub("[", "").gsub("", "]").split(",")
  1.080000   0.000000   1.080000 (  1.081227)


来源:https://stackoverflow.com/questions/17054738/convert-a-stringified-array-back-to-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!