count method

The count method takes an enumerable collection and counts how many elements match the given criteria. If no parameters are given, it returns the total number of elements in the collection. If a parameter is given, it returns the number of elements that match the given parameter. If a block is supplied, this method returns the total number of elements for which the block returned true.

Number List

@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

# count all numbers
@numbers.count  #=> 10

# count even numbers
@numbers.count(&:even?)  #=> 5

# count divisible by three
@numbers.count{|number| number % 3 == 0}  #=> 4

Pet Inventory

# count pets:
@inventory.count  #=> 7

# count in-stock pets:
@inventory.count(&:in_stock?)  #=> 6

# count pets with four legs:
@inventory.count{|pet| pet.legs == 4}  #=> 2

Pokey Things

# count pokey things with at least 3 letters:
@pokey_things.seek(0)
@pokey_things.map(&:chomp).count{|word| word.size >= 3}  #=> 4

# count pokey things with the letter 'e': 
@pokey_things.seek(0)
@pokey_things.count{|line| line.include?('e')}  #=> 3

Heroku Log File

# count heroku requests made via the GET method:
@requests.count(&:get?)  #=> 30

# count heroku requests with errors: 
@requests.count{|request| request.error?}  #=> 1

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>