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" ],
}
]