Created
April 25, 2018 23:29
-
-
Save cefaijustin/c1bf17b2d3538dce01aca0f6aa857144 to your computer and use it in GitHub Desktop.
This file contains 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
module Luhn | |
def self.is_valid?(number) | |
# ---------------------------------------------------- | |
# | |
# line 17 - take the number, convert it to a string | |
# and reverse it. '.chars' splits it by digit, then | |
# '.map' combined with (&:to_i) converts it to an integer. | |
# | |
# line 18 - 'sum' serves as a variable to push the numbers | |
# to once they are doubled / subtracted from, unless they're | |
# odd, in which case they are added to the variable as is. | |
reversedNums = number.to_s.reverse.chars.map(&:to_i) | |
sum = 0 | |
# ---------------------------------------------------- | |
# ---------------------------------------------------- | |
# | |
# line 32 - I need clarification on this. | |
# | |
# lines 33 - 35 add the numbers to sum, unless their | |
# position in the array is even, in which case they're | |
# multiplied by two. | |
# | |
# line 36 - I need clarification on this. | |
reversedNums.each_slice(2) do |odd, even| | |
sum += odd | |
next unless even | |
even *= 2 | |
even = even.divmod(10).inject(:+) if even > 9 | |
sum += even | |
end | |
return sum.modulo(10) == 0 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment