Convert a stringified array back to array

╄→尐↘猪︶ㄣ 提交于 2019-12-05 16:14:10
JSON.parse "[\"1018\", \"1037\", \"1045\", \"1042\"]"
#=> ["1018", " 1037", " 1045", " 1042"]
Mike

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.

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'}

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