I am receiving params like this "[[201], [511], [3451]]"
, I want to convert it into [201, 511, 3451]

- 99
- 7
-
I think the link below will help you. https://stackoverflow.com/questions/9593765/convert-array-values-from-string-to-int – Göksel Doğan Oct 14 '21 at 23:12
-
[I think the link below will help you.](https://stackoverflow.com/questions/9593765/convert-array-values-from-string-to-int) – Göksel Doğan Oct 14 '21 at 23:13
4 Answers
Let's say params is what you're receiving, you can use scan and map to use a Regular Expression, look for the digits in the response and then map each item in the array to an integer:
params = "[[201], [511], [3451]]"
params_array = params.scan(/\d+/).map(&:to_i)
What we are doing here is we are looking through the string and selecting only the digits with the Scan method, afterwards we get a string array so to convert it into integers we use the Map method. As per the map method, thanks to Cary Swoveland for the update on it.

- 31
- 6
-
-
1No attribution is needed. Incidentally, to keep your answers "clean", if you want to make an attribution I suggest you do it in a comment. – Cary Swoveland Oct 15 '21 at 05:36
It will help you!
str_arr = "[[201], [511], [3451]]"
JSON.parse(str_arr).flatten
or
eval(str_arr).flatten

- 69
- 6
-
Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 15 '21 at 10:08
here is an interesting way (note that it only works in case your params is an array string)
arr1 = instance_eval("[1,2,3]")
puts arr1.inspect # [1,2,3]
arr2 = instance_eval("[[201], [511], [3451]]")
puts arr2.inspect # [[201], [511], [3451]]

- 3,405
- 2
- 9
- 20
-
2
-
1Note the Rails tag and the use of the word _params_ which implies form data sent by the user agent. Doing this will allow the HTTP client to evaluate arbitrary Ruby code on the server. – Matheus Moreira Oct 15 '21 at 06:14
-
-
@user1934428 when i answered this question i even haven't thought about security, so `instance_eval` here is used for some cases the input array string maybe contains some specific values of the instance of the invoke class such as "[X, Y, Z]". – Lam Phan Oct 15 '21 at 07:21
First, I would make a sanity check that you don't get malevolent code injected:
raise "Can not convert #{params}" if /[^\[\]\d]/ =~ params
Now you can assert that your string is safe:
params.untaint
and then convert
arr = eval(params).flatten
or
arr = eval(params).flatten(1)
depending on what exactly you want to receive if you have deeply-nested "arrays" in your string.

- 19,864
- 7
- 42
- 87