Ruby — enumerable methods.
The enumerable methods were familiar yet different. The three most common methods are #each, #map and #filter. I’ve lifted the images from our coursework as the code-along elements really brought this topic to life.
The #each method is one that can access data in an array and return a value for each element without altering the original array.
The #map method will map through an original array and return a new array with the same length.
This also has a couple of built in variable names, #select or #find_all part of the conversational nature of Ruby programming. #filter unsurprisingly, filters an array and return elements based on a given condition.
Each of these methods have the same building blocks following the same pattern that of name_of_array/hash.ENUMERABLE do | variable | thing_to_do end
What are the || ?
Those are called “pipes”. When invoking an enumerable method like #map, the variable name inside the pipes acts as an argument that is being passed into the block. The method will pass, or yield, each element of the collection on which it is called to the block. Each element, as it gets passed into the block, will be equal to the variable name inside the pipes. Think of it like this:
- Call, or run, the code in the block once for each element of the collection.
- Pass a single element of the collection into the block every time the code in the block is called, or run. Start with the first element in the collection, and then move on to the second element, then the third, etc.
- Every time you call the code in the block and pass in an element from the collection, set the variable name from between the pipes equal to that element.
The value given to the pipes can be anything you want but it should be related to what you are trying to do to keep the code understandable.