Convert string array to array

I am using hstore with Postgres 9.2 and Rails 3.2 to store my object as follows:

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

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

How to convert this string to a Rails array? Even better, is there a way to store an array inside an hstore object so that Rails automatically retrieves it as an array type?

+3
source share
4 answers
JSON.parse "[\"1018\", \"1037\", \"1045\", \"1042\"]"
#=> ["1018", " 1037", " 1045", " 1042"]
+7
source

Why not just use it eval?

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

Obviously, do not do this on arbitrary or user-entered data, but on an array of integers, as you have shown, it is completely safe.

+6
source

:

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

, ,

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

, , , Vimsha, , :

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

:

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

: , , . - , 10 000 + . 100 000 :

  # "[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)
+1

Source: https://habr.com/ru/post/1732616/


All Articles