Skip to content

Instantly share code, notes, and snippets.

@Talha5
Created January 29, 2020 10:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Talha5/e67a98c2768a40c07ccff2194812e498 to your computer and use it in GitHub Desktop.
Save Talha5/e67a98c2768a40c07ccff2194812e498 to your computer and use it in GitHub Desktop.
Ruby - Credit Card
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
@Talha5
Copy link
Author

Talha5 commented Jan 29, 2020

TODOs(if time was enough):

  1. add specs
  2. multiple cards support

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