TODAY I LEARNED

Count similar items in an array in Ruby

Before ruby 2.7, you would have to do some hacky code like:

array.inject({}) {|f, v| f[v] ||= 0; f[v] += 1 ; f }

But starting with Ruby 2.7, there's a nicer way:

array.tally
irb: [1, 2, 3, 4, 4, 5, 5].tally
=> {1=>1, 2=>1, 3=>1, 4=>2, 5=>2}

Tweet

Learned by Edwin Cruz on Mar 11, 2021

Discover our latest blog posts
  • #sql
  • view raw
  • permalink
  • 1 likes
previous TIL next TIL
  • Log in
  • ?

    TIL is an open-source project by MagmaLabs that exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any MagmaLaber as well as selected friends of MagmaLabs. We hope you enjoy learning along with us.

    • /wearemagmalabs
  • statistics
  • search
  • Twitter