Skip to content

Instantly share code, notes, and snippets.

@joel29dec
Created June 30, 2019 20:37
Show Gist options
  • Save joel29dec/44fa82a9a522ed27a66a4255f9e0ecd8 to your computer and use it in GitHub Desktop.
Save joel29dec/44fa82a9a522ed27a66a4255f9e0ecd8 to your computer and use it in GitHub Desktop.
credit card validator in Ruby
cardnumber = 4012888888881881
def validlen?(arr)
#checks for card length of 13, 15, or 16
arr.length == 13 || arr.length == 15 || arr.length == 16
end
def arr_split(card_array)
#recieves array and select even or odd values and creates seperate arrays
select_odd_values = card_array.values_at(* card_array.each_index.select {|i| i.odd?})
select_even_values = card_array.values_at(* card_array.each_index.select {|i| i.even?})
if card_array.length.odd?
#maps the first array and muliftiply by 2
arr1 = select_odd_values.map{|e| e * 2}
arr2 = select_even_values
else
#maps the first array and multiply by 2
arr1 = select_even_values.map{|e| e * 2}
arr2 = select_odd_values
end
#returns an object of both arrays
arr = {"arr1" => arr1, "arr2" => arr2 }
end
def sum_arr_digits(array)
#convert to string and regex match for single digit and map to array
#reduce all digits
array.to_s.scan(/\d/).map(&:to_i).reduce(:+)
end
def validator(cardnumber)
#convert int to char and create array and convert char back to int
card_array = cardnumber.to_s.split(//).map{|char| char.to_i }
#pass array of int into length validator
if validlen?(card_array)
#collect array of both array in an object
split_arr = arr_split(card_array)
#Add all digits of both arrays together
checksum = sum_arr_digits(split_arr["arr1"]) + split_arr["arr2"].reduce(:+)
#Check if the checksum ends with a 0
if checksum % 10 == 0
type_validator_arr = card_array.slice(0,2)
#Int of the first numbers in the array
type_validator_int = type_validator_arr.join.to_i
if type_validator_arr[0] == 4
return "VISA"
elsif type_validator_int == 34 || type_validator_int == 37
return "AMERICAN EXPRESS"
elsif typeValidatorInt == 22 || typeValidatorInt == 51 || typeValidatorInt == 52 || typeValidatorInt == 53 || typeValidatorInt == 54
return "MASTERCARD"
elsif typeValidatorInt == 35
return "JCB"
elsif typeValidatorInt == 60
return "DISCOVER"
elsif typeValidatorInt == 30
return "DINERS CLUB"
end
else
return "INVALID"
end
else
return "INVALID"
end
end
puts validator(cardnumber)
@andreasantarl
Copy link

Hey! Great article in Medium! I enjoyed reading.

For line 50, you can write it a bit more concisely with the .include? method.
elsif [22, 51, 52, 53, 54].include? typeValidatorInt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment