user664833
user664833

Reputation: 19505

convert params array of numbers (a string) into an actual integer Array

I am sending an array ("[1,3,44,2,0]") via an Ajax PATCH call, and it arrives as:

Parameters: {"ids"=>"[1,3,44,2,0]"}

To taint check, I am using the following line - in which the match anchors against the start and end of the string, and makes sure that there is at least one digit, or that the numbers are comma separated:

raise "unexpected ids #{params[:ids]}" unless params[:ids].match(/\A\[(\d+,)*\d+\]\z/)

And to make an actual integer array out of it, I am using the following approach (strip the brackets, split on comma, convert each string element to an integer):

irb> "[1,3,44,2,0]"[1...-1].split(',').map {|e| e.to_i}
 => [1, 3, 44, 2, 0]

Is there a better (simpler, cheaper, faster) way of doing this?

Upvotes: 0

Views: 1328

Answers (1)

Ursus
Ursus

Reputation: 30056

Try

JSON.parse(params[:ids])

But I think you should check your Ajax call. It must be possible to pass the array not as a string.

Upvotes: 1

Related Questions