-
-
Save djrobby/2147723cd10b5fbd3612425bc8631e0c to your computer and use it in GitHub Desktop.
Ruby - Credit Card
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
class CreditCard | |
attr_accessor :card, :store | |
def initialize(card_identifier) | |
@card = card_identifier | |
@store = { | |
amex: {begins_with: ["34", "37"], number_length: ["15"]}, | |
discover: {begins_with: ["6011"], number_length: ["16"]}, | |
mastercard: {begins_with: ["51","52","53","54","55"], number_length: ["16"]}, | |
visa: {begins_with: ["4"], number_length: ["13", "16"]}, | |
} | |
end | |
def type | |
puts check_type(card) | |
end | |
private | |
def check_type(card_no) | |
card_company_name = nil | |
store.each do |card_name, params| | |
card_company_name = card_name if starts_with(params, card_no) && params[:number_length].include?(card_no.to_s.length.to_s) | |
end | |
card_company_name | |
end | |
def starts_with(params, card_no) | |
card_first_digits = card_no.to_s[0] | |
return true if params[:begins_with].include?(card_first_digits) | |
card_first_digits = card_no.to_s[0..1] | |
return true if params[:begins_with].include?(card_first_digits) | |
card_first_digits = card_no.to_s[0..3] | |
return true if params[:begins_with].include?(card_first_digits) | |
end | |
end | |
CreditCard.new(4111111111111111).type # :visa | |
CreditCard.new(4111111111111).type # :visa | |
CreditCard.new(4012888888881881).type # :visa | |
CreditCard.new(378282246310005).type # :amex | |
CreditCard.new(6011111111111117).type # :discover | |
CreditCard.new(5105105105105100).type # :mastercard | |
CreditCard.new(5105105105105106).type # :mastercard | |
CreditCard.new(9111111111111111).type # nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment