Map, Select, and Reduce Ruby Methods

Methods are chunks of code that were created by people to be used over and over by other programmers to make their life easier. Methods are used in a variety of ways to solve problems in a fast and efficient way. This blog post will talk about Map, Select, and Reduce methods in detail.

Map

The map method iterates through an array for each of the elements and passes each element to the block. The block executes the code on each element and the return value is pushed to the final new array. After the map method has iterated through the entire array the return value is a new array containing the transformed elements from the original array.

Array#map example

Here the Array#map method iterates through each element in the array. It invokes the given block once for element and the block is concatenating an "!"to every string and returns that value to the map method. After the method has iterated through every element in the array it returns a new array containing the values returned by the block.

Map use cases

The map method is good for performing transformations on the elements inside an object. If the object is an array with integers as the elements and you needed to multiply every element by 2 map is perfect for that. if you needed to capitalize every word in an array map is perfect for that. if you need to convert strings to integers map is perfect for that as well.

Example use case

Use case example 1

arry = ["2","56","1","23","4"]

arr1 = arry.map do |str|

str.to_i

end

p arr1 #=> [2,56,1,23,4]

In the code example above arryis initiated with strings as elements. The map method is used on arryto iterate through each element in the array and passes each element to the block. The block str.to_iconverts each string element to an integer and returns that value to the map method. Once the map method has iterated through each element it returns a new array containing all the transformed elements from the original array. arr1 captures the map methods return value and p arr1 outputs an array with integers as the elements.

Use case example 2

arry = [2,56,1,23,4]

arry1 = arry.map do |x|

x * 2

end

p arry1 #=> [4,112,2,46,8]

In the code example above arryis initiated with integers as elements. The map method is used on arryto iterate through each element in the array and passes each element to the block. The block x * 2 multiplies each element by 2 and returns that value to the map method. Once the map method has iterated through each element it returns a new array containing all the transformed elements from the original array. arr1 captures the map methods return value and p arr1outputs an array with the integers multiplied by 2.

Use case example 3

arry = ["hello”,"world","whatsup"]

arry1 = arry.map do |str|

str.capitalize

end

p arry1 #=> ["Hello","World","Whatsup"]

In the code example above arryis initiated with strings as elements. The map method is used on arryto iterate through each element in the array and passes each element to the block. The block str.capitalizecapitalizes each string element returns that value to the map method. Once the map method has iterated through each element it returns a new array containing all the transformed elements from the original array. arr1 captures the map methods return value and p arr1outputs an array with each string in their capitalized form.

Select

The select method iterates through an enumerable object for which the given block returns a truthy or falsie value. If the block returns a truthy value the select method takes that element and puts it in a new enumerable object. If the block value returns falsie the select method ignores that element. After the method has iterated through all the elements it returns a new enumerable object.

Hash#select example

Here the Hash#select method iterates through each element (key/value pair) in the hash. It invokes the given block once for each element. The block is checking to see if the key is greater than the string "a"and returns a Boolean value. The select method is only concerned with the truthiness of the value of the block. After the method has iterated through each element the select method creates a new hash consisting of entries for which the block returns true.

Array#select example

In this example the Array#select method is used. Its process is practically the same. The method iterates through each element in the array and invokes the given block once for each element. The block is checking to see if the numbers in the array are even and returns a Boolean value. The select method is only concerned with the truthiness of the value of the block. After the method has iterated through each element, the select method creates a new array containing all elements of the original array for which the given block returns a true value.

Select use cases

The select method is good for selecting a subset of elements based on a criteria described in the block. Select can be used to capture even integers inside an array that contains integers. If you have an array of strings you can use the select method to create a subset of that array containing strings that have an odd number of characters. If you have a hash that contains 50 houses as the keys and their square footage as the values, you can use the select method to create a subset of that hash containing houses with less than 1800 square feet.

Example use case

Use case example 1

arr = ["hello","five","yes","no"]

arr1 = arr.select do |str|

str.length.odd?

end

p arr1 #=> ["hello", "yes"]

In the code sample above arris initialized with strings as elements. The select method is used on arrto iterate through each element in the array and passes each element to the block. The block str.length.odd? calculates the amount of characters per string and returns a true or false value (true if the amount of characters are odd and false if even). The select method is only concerned with the truthy values returned by the block. After the select method has iterated through each element in the arrarray, the method returns a new array consisting of only the values that evaluated to true by the block. arr1captures the select methods return value and p arr1outputs an array with strings with an odd amount of characters.

Use case example 2

arr = [1,2,3,4,5,6,7,8,9]

arr1 = arr.select do |x|

x.even?

end

p arr1 #=> [2,4,6,8]

In the code sample above arr is initialized with integers as elements. The select method is used on arrto iterate through each element in the array and passed each element to the block. The block x.even? checks to see if the element is even and returns true (true if even, false if odd). The select method is only concerned with the truthy values returned by the block. After the select method has iterated through each element in the arrarray, the method returns a new array consisting of only the values that evaluated to true by the block. arr1captures the select methods return value and p arr1outputs an array with even integers.

Use case example 3

hsh = {house1: 1000, house2: 1100, house3: 2200, house4: 1800, house5: 2900, house6: 4500, house7: 1750, house8: 3200, house9: 2000, house10:1500}

hsh1 = hsh.select do |k,v|

v > 1800

end

p hsh1 #=> {:house3=>2200, :house5=>2900, :house6=>4500, :house8=>3200, :house9=>2000}

In the code sample above hsh is initialized with houses as keys and values as square footage. the select method is used on hsh to iterate through each element (key/value pair) in the hash and passed each element to the block. the block v > 1800 checks to see if the value is greater than 1800 and returns true. The select method is only concerned with the truthy values returned by the block. After the select method has iterated through each element in the hsh hash. The method returns a new hash consisting of only the values that evaluated true by the block. hsh1 captures the select methods return value and p hsh1outputs a hash with houses that have a greater square footage of 1800.

Reduce

The reduce method combines all the elements of an enumerable by applying a binary operation.

If specified by a block, then each element is passed with an accumulator. After each iteration the accumulator is updated by the return value of the block. At the end of the iteration, the final value of the accumulator is the return value of the reduce method.

If a symbol is specified instead, then each element in the collection will be passed to the binary operation. The first element becomes the initial accumulator value. The accumulator value is updated by the binary operation with the next element. At the end of the iteration, the return value for the reduce method is the final accumulator value.

Block example

Here the reduce method is specified with a block. The range from 5 to 10 are multiplied by the product. productstarts at 1 and its value is updated after each iteration. Meaning on the first iteration the block executes 1 * 5. After the block executes productbecomes 5. The second iteration the block executes 5 * 6. The value of productbecomes 30 and this process continues until the end of the range. At the end of the iteration, the return value of the method is the final value of the accumulator 151200.

Symbol example

Here the reduce method is specified with a +symbol so the integers in a range from 5 to 10 are added up and the total value 45 is returned. The first value of the accumulator is the first element of the range 5. The accumulator is updated by the + symbol and the next element in the range 6is added. This process is repeated until the block reaches the last element in the range. The return value of the reduce method is the final accumulator value 45.

Reduce use cases

The reduce method is a good shorthand way for adding and multiplying a range or an array of numbers, or even keeping track of the biggest/smallest string inside an array without writing a loop. If you wanted to add up all the values inside an array reduce is perfect for that. If you wanted to multiply all the elements inside an array reduce is perfect for that. If you wanted to find out whats the biggest/smallest word inside an array reduce is perfect for that.

Example use case

Use case example 1

arry = [5,6,7,8,9]

p arry.reduce(:*) #=> 15120

In the code sample above arryis initialized with integers as elements. The reduce method is used on arryto multiply all the integers together as deemed by the * symbol. The reduce method starts with the first integer in the array 5 and multiplies with the next integer. This process continues until all the integers in the array have been multiplied and the total accumulator value is returned in a integer format. The reduce methods return value is the final accumulator value.

Use case example 2

longest = %w{ cat sheep bear}.reduce do |memo, word|

memo.length > word.length ? memo : word

end

p longest #=> "sheep"

In the code sample above the array w{ cat sheep bear} is initialized with strings as elements. The reduce method is used on the array to figure out which string has the most characters. The block memo.length > word.length ? memo : word compares the strings lengths. memo acts as the accumulator and word represents the current element as we iterate through the array. If word.lengthis greater than memo.length then word becomes memo and the next comparison begins until the reduce method has fed all the strings to the block. The block returns the final accumulator value to the reduce method. The reduce methods return value is the final accumulator value. The variable longest captures the return value and p longestoutput is a string value.

Use case example 3

arry = [5,6,7,8,9]

p arry.reduce(:+) +=> 35

In the code sample above arry is initialized with integers as elements. The reduce method is used on arry to add up all the integers together as deemed by the + symbol. The reduce method starts with the first integer in the array 5 and adds with the next integer. This process continues until all the integers in the array have been added and the total accumulator value is returned in a integer format. The reduce methods return value is the final accumulator value.