Home > other >  Convert string arra into array of integers
Convert string arra into array of integers

Time:10-15

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

CodePudding user response:

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.

CodePudding user response:

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]]

CodePudding user response:

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.

  • Related