Last Updated:

Convert URL address bar parameters to a hash - Ruby

Having searched the Internet for a way to parse the command line, I decided to replenish the list of homemade and parser lovers. Perhaps someone will find this code useful.

So, the task was as follows: it was necessary to parse a set of parameters of the URL address string, with the ability to receive arrays. Having searched the Internet for a solution to this problem, I decided that it would be faster to do what I needed myself.

The main iteration of the parameter disassembly can be divided conditionally into two parts.

 

Prepare a parameter string for recursive processing. For example, a parameter of the form "g[b][e][]=2" is converted to an array whose main property is the nesting of arrays whose dimension does not exceed two elements "["g", ["b", ["e", ["", [""", "2"]]]]]". Empty strings in this set are treated as a feature of the array "[]" and the sign is "=".

Example of preparing an array for a parameter with a finite value of type array "[]"

Example of preparing an array for a parameter with a finite value of type string or number "..."

Subsequent processing of the array is performed by a recurrent lambda function. As parameters, this function takes a partially populated hash of the parameters and an array. The lambda function complements or recreates a parameter in the input hash based on the chain embedded in the array. I suppose, looking at the array, it will not be difficult to understand how the lambda function works.

 

This function parses parameters of the form "g[b][e][]=1&g[b][e][]=2&g[b][e][]=34&g[b][c]=d", but alas, it is not designed to parse an array of complex objects, for example, "g[][b][e][e][]=expression". The array for this function can only be a finite value.

Example of how the function works

Fans of dry-code I suggest to make amendments