Skip to content

Instantly share code, notes, and snippets.

@amkurian
Last active February 13, 2020 12:17
Show Gist options
  • Save amkurian/819834f3c6221ce0c7d83fdd826cda51 to your computer and use it in GitHub Desktop.
Save amkurian/819834f3c6221ce0c7d83fdd826cda51 to your computer and use it in GitHub Desktop.

Array#count

Ever wondered how much power Ruby's count method has? Besides counting the elements of an array, it can do pretty awesome things. So let's start with the most common use case: counting the elements of an array.

irb> numbers = [1,2,5,3,6,2,5,3]
 => [1, 2, 5, 3, 6, 2, 5, 3]
irb> numbers.count
 => 8

Let's say you want to count how often the number 3 is represented in the array. You could use a loop to iterate over the array and increment a counter every time you see the number 3, but there is a better way... Just pass the object you're looking for to the count method!

irb> numbers = [1,2,5,3,6,2,5,3]
 => [1, 2, 5, 3, 6, 2, 5, 3]
irb> numbers.count(3)
 => 2

Finally, you can also pass a block to execute more complicated counts.

irb> numbers = [1,2,5,3,6,2,5,3]
 => [1, 2, 5, 3, 6, 2, 5, 3]
irb> numbers.count(&:even?)
 => 3

The method above is basically shorthand for numbers.count{|n| n.even?}.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment