0

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

Warden
  • 99
  • 7

4 Answers4

2

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.

Gameza
  • 31
  • 6
1

It will help you!

str_arr = "[[201], [511], [3451]]"

JSON.parse(str_arr).flatten

or

eval(str_arr).flatten
  • 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
0

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]]
Lam Phan
  • 3,405
  • 2
  • 9
  • 20
  • 2
    You could use `p` instead of writing `puts` with `inspect` – Rajagopalan Oct 15 '21 at 03:25
  • 1
    Note 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
  • @LamPhan : Why `instance_eval` and not `eval`? – user1934428 Oct 15 '21 at 06:53
  • @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
0

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.

user1934428
  • 19,864
  • 7
  • 42
  • 87