Skip to content

Instantly share code, notes, and snippets.

@kossoff
Created March 12, 2021 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kossoff/2b3d5b7a0b70c80f550d0e4a9e457551 to your computer and use it in GitHub Desktop.
Save kossoff/2b3d5b7a0b70c80f550d0e4a9e457551 to your computer and use it in GitHub Desktop.
def luhn(code)
(code
.chars # Break into individual digits
.map(&:to_i) # map each character by calling #to_i on it
.reverse # Start from the end
.map.with_index { |x, i| i.odd? ? x * 2 : x } # Double every other digit
.map { |x| x > 9 ? x - 9 : x } # If > 9, subtract 9 (same as adding the digits)
.inject(0, :+) % 10).zero? # Check if multiple of 10
end
p luhn(ARGV[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment