The problem would be easy to solve with a manual loop and a result array, which you add onto as you go. But I’m looking for a more ruby-esque solution, probably something that uses inject or select. Here’s the problem:
arr_of_hashes = [
{id: 1, val: "blah1"},
{id: 1, val: "blah2"},
{id: 1, val: "blah3"},
{id: 2, val: "blah4"},
{id: 2, val: "blah5"},
{id: 3, val: "blah6"},
{id: 3, val: "blah7"},
{id: 3, val: "blah8"},
{id: 3, val: "blah9"}
]
“Groups” are defined by the “id” field in the hashes. We are guaranteed each group has at least two items. We want to return an array containing the 2nd item of each group:
output_should_be = [
{id: 1, val: "blah2"},
{id: 2, val: "blah5"},
{id: 3, val: "blah7"}
]
“I’m looking for a more ruby-esque solution”. I guess you mean functional:
Use
group_byif elements are not pre-ordered by id.