"Enumerable", in Ruby, is a set of methods for collections. They are used in all the common collection classes. This command will tell you which classes. Try to guess a few before you run it:
$ ruby -e 'p ObjectSpace.each_object(Class).select { |c| c < Enumerable }'
To use Enumerable, a class needs to define its own each
method, all Enumerables are abstractions on top of each
.
Lets figure out how map
works, together using Seeing Is Believing.
Here are a set categories, turn each one into a comment, and place each enumerable method beneath the given category with a description of what it does and an example to illustrate it. When we are done, we will have a cheatsheet we can refer back to, and it will be runnable with Seeing Is Believing. If, after several tries, you don't have any good idea how to use it, you can look at the documentation
- Enumerable methods that iterate over a collection
- Enumerable methods that filter a collection
- Enumerable methods that return true or false
- Enumerable Methods that Distill a Collection to One Value
- Enumerable Methods that Return New-Shaped Collections
Here are the methods to categorize. Pay attention to all information available to you. What might the name mean? Does it blow up if you give it an argument? What might that name mean if it takes an argument? Did it do nothing interesting? Maybe it takes a block, what might go in the block? What might the block receive? How can you answer those questions? (hint: Seeing Is Believing)
to_a
count
find
find_all
map
inject
group_by
each_with_object
take
drop
each_with_index
first
all?
any?
none?
min
min_by
max
max_by
include?
sort
zip
We have a large number of small focused tests to try and illustrate the patterns in Enumerable. Work through them until they are all passing: enums-exercise
If you would like to see me code, I implemented Enumerable on video here.