Skip to content

Instantly share code, notes, and snippets.

@lkrych
Created November 8, 2016 02:02
Show Gist options
  • Save lkrych/fff9660d858dff696e7ac0cc2e9568ce to your computer and use it in GitHub Desktop.
Save lkrych/fff9660d858dff696e7ac0cc2e9568ce to your computer and use it in GitHub Desktop.
Naive Ruby implementation of checksum algorithm
def credit_card_check() #main ruby method
credit_card_no = 0
loop do #get credit card number
puts "Number: "
credit_card_no = gets.chomp
size = credit_card_no.to_s.size
break if size >= 13 && size <= 16
end
cardValid = checkCredit(credit_card_no)
if cardValid == false
puts "INVALID"
return
elsif credit_card_no.to_s[0] == "5"
puts "MASTERCARD"
elsif credit_card_no.to_s[0] == "4"
puts "VISA"
elsif credit_card_no.to_s[0] == "3"
puts "AMEX"
end
end
def checkCredit(card_no) #helper_method that implements checksum
evenSum = 0
odd = []
card_no.to_s.reverse.split("").each_with_index do |digit, idx|
if idx == 0 || idx % 2 == 0
evenSum += digit.to_i
else
odd.push(digit.to_i * 2)
end
end
oddSum = sumDigits(odd)
#puts "Odd Sum: #{oddSum}, Even Sum: #{evenSum}"
if (oddSum + evenSum) % 10 == 0
return true
else
return false
end
end
def sumDigits(arr) #helper_method that adds the digits of numbers in an array
sum = 0
arr.each do |number|
if number > 9
sum += number % 10
sum += 1
else
sum += number
end
end
return sum
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment