Warden
Warden

Reputation: 109

Convert string arra into array of integers

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

Upvotes: 0

Views: 174

Answers (4)

Edil Talantbekov
Edil Talantbekov

Reputation: 84

It will help you!

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

JSON.parse(str_arr).flatten

or

eval(str_arr).flatten

Upvotes: 1

user1934428
user1934428

Reputation: 22217

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.

Upvotes: 0

Gameza
Gameza

Reputation: 41

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.

Upvotes: 2

Lam Phan
Lam Phan

Reputation: 3811

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

Upvotes: 0

Related Questions