Skip to content

Latest commit

 

History

History
46 lines (35 loc) · 699 Bytes

combine_elements_in_collection.md

File metadata and controls

46 lines (35 loc) · 699 Bytes

Combine operation in collections (enumerables)

Given the following collection:

values = [1, 2, 3, 4]

Combine elements with reduce

An operation such as:

product = 1
values.each { |value| product *= value }
product
# => 24

Can be simplified with reduce method:

values.reduce(:*)
# => 24

Combine elements with inject

An operation such as:

hash = {}
values.each do |value|
  hash.merge(value => value ** 2)
end
hash
# => { 1 => 1, 2 => 4, 3 => 9, 4 => 16 }

Can be simplified with inject method:

values.inject({}) do |hash, value|
  hash.merge(value => value ** 2)
end
# => { 1 => 1, 2 => 4, 3 => 9, 4 => 16 }