Last active
November 8, 2016 16:29
-
-
Save lkrych/238dbf1fd2027dc624cf8a740b2e2d26 to your computer and use it in GitHub Desktop.
Refactored ruby implementation of credit problem.
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 credit_card_check() #main ruby method | |
| credit_card_no = 0 | |
| until [13,14,15,16].include? credit_card_no.to_s.size #get credit card number | |
| puts "Number: " | |
| credit_card_no = gets.chomp | |
| end | |
| cardValid = checkCredit(credit_card_no) | |
| if cardValid == false | |
| puts "INVALID" | |
| else | |
| credit_key = {"5" => "MASTERCARD", "4" => "VISA", "3" => "AMEX" } | |
| puts credit_key[credit_card_no.to_s[0]] | |
| end | |
| end | |
| def checkCredit(card_no) #helper_method that implements checksum | |
| evenSum = 0 | |
| oddSum = 0 | |
| card_no.to_s.reverse.split("").each_with_index do |digit, idx| | |
| if idx == 0 || idx % 2 == 0 | |
| evenSum += digit.to_i | |
| else | |
| double = digit.to_i * 2 | |
| oddSum += double > 10? (double % 10) + 1 : double # use ternary operator as stand in for sumDigits | |
| end | |
| end | |
| (oddSum + evenSum) % 10 == 0 ? true : false | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment