Skip to content

Instantly share code, notes, and snippets.

@12joan
Created March 1, 2022 14:54
Show Gist options
  • Save 12joan/2ef46139b59cf7ab4dd723744a65dcdb to your computer and use it in GitHub Desktop.
Save 12joan/2ef46139b59cf7ab4dd723744a65dcdb to your computer and use it in GitHub Desktop.
# Version 1: Using a loop counter to emulate a C-style for loop.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
product = 1
i = 0
while i < numbers.size
product *= numbers[i]
i += 1
end
# Version 2: Avoiding the use of a loop counter using `each`.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
product = 1
numbers.each do |n|
product *= n
end
# Version 3: Generating the array using `upto`.
numbers = 1.upto(12)
product = 1
numbers.each do |n|
product *= n
end
# Version 4: Using a block with `upto` instead of using `each`.
product = 1
1.upto(12) do
product *= n
end
# Version 5: Abstracting away the accumulator variable pattern using `reduce`.
product = 1.upto(12).reduce { |acc, n| acc * n }
# Version 6: Using an alternative form of `reduce` to avoid the need for a block.
product = 1.upto(12).reduce(:*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment