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-specific behaviors.
• The class requiring the Enumerable module must have an #each
method because the additional collection-specific behaviors given
by Enumerable are defined 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 define #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 modifies each member according to
instructions in a block and returns the modified 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