I have unsorted map of key value pairs.
input = { 'xa' => 'xavalue', 'ab' => 'abvalue', 'aa' => 'aavalue', 'ba' => 'bavalue', }
Now I want to sort them by the key and cluster them into sections by the first character of the key. Similar to this:
output1 = { 'a' => { 'aa' => 'aavalue', 'ab' => 'abvalue', }, 'b' => { 'ba' => 'bavalue', }, 'x' => { 'xa' => 'xavalue', }, }
-
While this is relatively trivial I am looking for a concise way to express this transformation from input to output1 in ruby. (My approach is probably too verbose as to ruby standards)
-
You might also have noticed that maps are (usually) not ordered. So the above data structure will not work appropriately unless I manually sort the keys and wrap the access to the map. So how would I create a key ordered map in ruby? Or is there one already?
-
If the ordered map approach is not that easy I would have to change the final structure into something like the following. Again I am looking for some concise ruby code to come from input to output2.
.
output2 = [ { 'name' => 'a', 'keys' => [ 'aa', 'ab' ], 'values' => [ 'aavalue', 'abvalue' ], }, { 'name' => 'b', 'keys' => [ 'ba' ], 'values' => [ 'bavalue' ], }, { 'name' => 'x', 'keys' => [ 'xa' ], 'values' => [ 'xavalue' ], } ]
As far as I know, there isn’t the notion of a sorted hash/map in Ruby, so you’re limited to good old arrays for this one. You may want to start from this code:
This will give you a data structure in the form
By mapping the component arrays into hashes…
You can transform it into something like
With a similar map, you can get to the last form you listed (output2):