Created
March 1, 2022 14:54
-
-
Save 12joan/2ef46139b59cf7ab4dd723744a65dcdb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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