Cheat Sheet Content for working with Enumerables
1. What do we want to know about Enumerables?
The Enumerable is a module and its mixin provide collection classes with methods to traverse, search, sort & manipulate collections.
Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.
- Modules provide a namespace and prevent name clashes.
- Modules implement the mixin facility.
Enumberable is a module that can be used as a mixin the following classes: Hashes, Arrays, Sets, Ranges, & Structs.
2. What would be good to have on hand when working Enumberables?
Commonly used Enumberable Methods -
cycle:
Kind of like each, but you can run the code block multiple times, if no argument is given, it runs forever.
arr = ["a", "b", "c"] arr.cycle { |x| puts x } # print, a, b, c, a, b, c,.. forever. arr.cycle(2) { |x| puts x } # print, a, b, c, a, b, c.
each_slice:
Cuts the array into slices based on the argument.
(1..10).each_slice(3) { |slice| p slice } # outputs below [1, 2, 3] [4, 5, 6] [7, 8, 9] [10]
max_by:
Find something in the array by stating the criteria in the code block.
arr = [albatross, dog, horse] arr.max_by { |x| x.length } #=> "albatross"
If the n argument is given, minimum n elements are returned as an array.
arr = [albatross, dog, horse] arr.max_by(2) {|x| x.length } #=> ["albatross", "horse"]
drop:
If an argument n is given, drop deletes the first n elements in the array.
arr = [1, 2, 3, 4, 5, 0] arr.drop(3) #=> [4, 5, 0]
drop_while:
Delete all elements in an array that fits the criteria stated in the code block.
arr = [1, 2, 3, 4, 5, 0] arr.drop_while { |i| i < 3 } #=> [3, 4, 5, 0]
partition:
Returns two arrays, the first containing the elements of array for which the block evaluates to true, the second containing the rest.
partition: { |obj| block } → [ true_array, false_array ] (1..6).partition { |v| v.even? } #=> [[2, 4, 6], [1, 3, 5]]
grep:
Return all the values in a collection that matches the pattern given in the argument.
(1..100).grep(38..44) #=> [38, 39, 40, 41, 42, 43, 44]
3. ENUMBERABLE is ruby's way of saying that we can get elemenents our of a collection one at a time.
Definition: Enumerate - mention number of things, one by one.
The Enumberable module itself doesnt define the #each method. It's responsiblity of the class that is including this module to do so.
4. What is the point of returning and Enumerator?
Using an Enumerator vs an Array: for an Enumerator you can go through this set of collections one by one. As oppose to an Array where you would have to break the the collection.