basic-enumerable-methods
# Metadata
2022-06-03 18:42 | basic-enumerable-methods | Doriel Rivalet
# Content
The do is optional in a for loop in Ruby and may cause issues if used in IRB
| block variable |
This is the element from your array that the block is currently iterating over. You can use any variable name that you find helpful here
For multi-line blocks, the commonly accepted best practice is to change up the syntax to use do...end
instead of {...}
:
#map
method (also called #collect
) transforms each element from an array according to whatever block you pass to it and returns the transformed elements in a new array.
its like commutativity of multiplication a*b, a being the array element and b being the block
|
|
#select
method (also called #filter
)
#reduce
is replacement for accumulator variables
#reduce
method (also called #inject
)
|
|
|
|
bang methods make the methods destructive, mutates the object.
the ruby way
|
|
enumerable methods are used on both arrays and hashes
Enumerable Iterators Cheat Sheet
#each
returns the original object it was called on because it’s really used for its side effects and not what it returns#each_with_index
passes not just the current item but whatever position in the array it was located in.#select
returns a new object (e.g. array) filled with only those original items where the block you gave it returnedtrue
#map
returns a new array filled with whatever gets returned by the block each time it runs.
The full list is available in the docs here.
#any?
returns true/false (see the question mark?) and answers the question, “do ANY of the elements in this object pass the test in my block?”. If your block returns true on any time it runs,any?
will return true.#all?
returns true/false and answers the question, “do ALL the elements of this object pass the test in my block?”. Every time the block runs it must return true for this method to return true.#none?
returns true only if NONE of the elements in the object return true when the block is run.#find
returns the first item in your object for which the block returns true.
Awesome but less common methods
#group_by
will run your block and return a hash that groups all the different types of returns from that block. For example:1 2 3
> names = ["James", "Bob", "Joe", "Mark", "Jim"] > names.group_by{|name| name.length} => {5=>["James"], 3=>["Bob", "Joe", "Jim"], 4=>["Mark"]}
#grep
returns an array with those items that actualy match the specified criteria (RegEx) (using a===
match)1 2
> names.grep(/J/) => ["James", "Joe", "Jim"]
|
|
.each{key value} .each_with_index{value key}
# Sources
Own notes
https://www.theodinproject.com/lessons/ruby-basic-enumerable-methods
https://www.rubyguides.com/2018/10/ruby-map-method/
# Content Lists
If you prefer browsing the contents of this site through a list instead of a graph, you can find content lists here too: