Skip to content

Instantly share code, notes, and snippets.

@junegunn
Created December 18, 2019 10:05
Show Gist options
  • Select an option

  • Save junegunn/e4097ec8acaf0a2a6b6ce062ab5f08ed to your computer and use it in GitHub Desktop.

Select an option

Save junegunn/e4097ec8acaf0a2a6b6ce062ab5f08ed to your computer and use it in GitHub Desktop.

Revisions

  1. junegunn created this gist Dec 18, 2019.
    20 changes: 20 additions & 0 deletions array-of-hashes.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    data = [{ a: 1, b: 9 }, { a: 1, b: 8 },
    { a: 2, b: 7 }, { a: 2, b: 6 }]

    data.group_by { |h| h[:a] }.transform_values { |xs| xs.max_by { |x| x[:b] } }


    def key(k)
    proc { |hash| hash[k] }
    end

    data.group_by(&key(:a)).transform_values { |xs| xs.max_by(&key(:b)) }


    class Array
    def to_proc
    proc { |hash| hash[first] }
    end
    end

    data.group_by(&[:a]).transform_values { |xs| xs.max_by(&[:b]) }