2. WHY USE ENUMERABLES
âą Ruby's Enumerable module has methods for all kinds of tasks
which operate on a collection.
âą If you can imagine a use for the #each method other than simply
iterating, there is a good chance a method exists to do what you
have in mind.
3. WHAT DOES ENUMERABLE
MEAN?
âą Collection objects (instances of Array, Hash, etc) typically âmixinâ
the Enumerable module
âą The Enumerable module gives objects of collection classes
additional collection-speciïŹc behaviors.
âą The class requiring the Enumerable module must have an #each
method because the additional collection-speciïŹc behaviors given
by Enumerable are deïŹned in terms of #each
9. EACH
âą Classes that include the Enumerable module must have an #each
method.
âą The #each method yields items to a supplied code block, one
at a time
âą Different Classes deïŹne #each differently
âą Array: #each yields each element
âą Hash: each yields #each key/value pair as a two-element array
>> v_names = %w(car truck bike)
=> ["car", "truck", "bike"]
>> v_names.each do |vehicle|
?> puts vehicle
>> end
10. MAP
âą The map method modiïŹes each member according to
instructions in a block and returns the modiïŹed collection of
members.
>> v_names.map { |v| v.upcase}
=> ["CAR", "TRUCK", "BIKE"]
11. GREP
âą The grep method 'searches' for members using a regular
expression.
>> v_names.grep /a/
=> ["car"]
>> v_names.grep(/a/) { |v| v.upcase}
=> ["CAR"]
13. ALL?
âą The all? method returns true if all of the members of a collection
satisfy the evaluation of the block. Otherwise it returns false.
>> v_names.all? { |v| v.length > 2}
=> true
>> v_names.all? { |v| v.length > 10}
=> false
14. ANY?
âą The any? method returns true if any of the members of a
collection satisfy the evaluation of the block. Otherwise it returns
false.
>> v_names.any? { |v| v.length == 3}
=> true
>> v_names.any? { |v| v = "car"}
=> true