I send an array from rest client and received it like this: "[1,2,3,4,5]"
Now I just want to convert it into Array without using Ruby's eval method. Any Ruby's default method that we could use for this?
"[1,2,3,4,5]" => [1,2,3,4,5]
I send an array from rest client and received it like this: "[1,2,3,4,5]"
Now I just want to convert it into Array without using Ruby's eval method. Any Ruby's default method that we could use for this?
"[1,2,3,4,5]" => [1,2,3,4,5]
require 'json'
JSON.parse "[1,2,3,4,5]"
#=> [1, 2, 3, 4, 5]
JSON.parse "[[1,2],3,4]"
#=> [[1, 2], 3, 4]
Perhaps this?
s.tr('[]', '').split(',').map(&:to_i)
'["12", "45"]'.tr('[]','').map(&:to_i) it return error : undefined method mapJSON.parse lol. But if you reallyyyyy wanted, '["12", "45"]'.tr('["]','').split(',')ArgumentError for non-integers like '2.2' or bad data like '2sdf' then replace the .map(&:to_i) at the end with .map { |x| Integer(x) }. (Or .map { |x| Float(x) } if you want floats).If you want to avoid eval, yet another way:
"[1,2,3,4,5]".scan(/\d+/).map(&:to_i) #assuming you have integer Array as String
#=> [1, 2, 3, 4, 5]
'[88,89,100]'.scan(/\d/) returns ["8", "8", "8", "9", "1", "0", "0"]\d+ will solve this. I have updated my answer. ThanksJSON.parse @VishwasNahar