Kunal Mahajan: Dev BootCamp

"The tale of my journey on becoming a Junior Web Developer..."

Kunal's Picture

DBC-Technical Blog:

Date: 08.01.15
Entry #: 4

Commentary:

So today...I wanted to discuss an important Enumerable method called 'map'. The Enumerable, (a module that includes the ability to search/sort) includes a method called "map" that allows us to iterate over every element in an array and whatever gets returned in that block of code, gets added to a new array.

For example:

arr = [12,23,45,56,67,78,89,90,100]
/defines an array with numerical digits.

p arr
/prints results of the array to user.

p arr.map(&:odd?).select { | e | e == true}
/takes the array, applies the map method and iterates over every element running a block of code that checks every element; if any elements are found to be odd, places them into another array and prints it out in an array format.

p arr.map(&:odd?).select { | e | e == true}.count
/counts the amount of true values that have been found from the array and prints it to user in a numerical value.

I wanted to give credit, where credit is due as this gentleman did a fine job explaining visually what is actually going on: MattStopaDev