I’m new to Ruby and am working on a CLI application that parses some reports of mine. I would like to figure out the most efficient way to achieve the following with this line:
MAXCONN: 2000, MAXSSL_CONN: 500, PLAINCONN: 34, AVAILCONN: 1966, IDLECONN: 28, SSLCONN: 0, AVAILSSL: 500
I would like to map this into a hash accordingly:
{ :maxconn => 2000, :maxssl_conn => 500, :plainconn => 34, :availconn => 1966, :idleconn => 28, :sslconn => 0, :availssl => 500 }
The only way I can think to do this is to split at the comma and then again at the semi-colon and map them.
I have a sneaking suspicion there may be some Ruby magic to achieve this in a more efficient and less cumbersome way.
Any input and or tricks / tips would be appreciated as I have a feeling I’ll be approaching problems like this relatively often.
We combine the technique for converting a bunch of key-value pairs into a hash
with the regular expression method
String#scan, which passes through a string and collects matches in an array, to getThis also uses a block with
Enumerable#mapthat interprets arrays as pairs of(first, second)elements in the argument list, extracts these into new elements, and applies conversions to them so as to tailor the resulting hash to your example’s specifications (otherwise, you just get a hash of strings mapping to strings).