Last active
August 29, 2015 14:20
-
-
Save danimal141/3bd6417a727326587752 to your computer and use it in GitHub Desktop.
Luhn checksum
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
def check_sum val | |
sum = val.to_s.each_char.with_index.inject([]) do |memo, (char, i)| | |
next memo << double_digit_value(char.to_i) if i.odd? | |
memo << char.to_i | |
memo | |
end.inject :+ | |
if (sum % 10).zero? | |
p "#{sum} is divisible by 10. Valid!" | |
else | |
p "#{sum} is not divisible by 10. Invalid!" | |
end | |
end | |
def double_digit_value digit | |
double_digit = digit * 2 | |
sum = double_digit > 10 ? (1 + double_digit % 10) : double_digit | |
return sum | |
end | |
puts 'Enter some number' | |
input_val = gets.chomp | |
begin | |
check_sum input_val | |
rescue => e | |
p e | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment