Given the following collection:
values = [1, 2, 3, 4]
An operation such as:
product = 1
values.each { |value| product *= value }
product
# => 24
Can be simplified with reduce
method:
values.reduce(:*)
# => 24
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 }
Or with the each_with_object
method:
values.each_with_object({}) do |value, hash|
hash[value] = value ** 2
end
# => { 1 => 1, 2 => 4, 3 => 9, 4 => 16 }