Skip to content

Instantly share code, notes, and snippets.

@danimal141
Last active August 29, 2015 14:20
Show Gist options
  • Save danimal141/3bd6417a727326587752 to your computer and use it in GitHub Desktop.
Save danimal141/3bd6417a727326587752 to your computer and use it in GitHub Desktop.
Luhn checksum
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