Skip to content

Instantly share code, notes, and snippets.

@aharpole
Last active August 29, 2015 13:56
Show Gist options
  • Save aharpole/8925320 to your computer and use it in GitHub Desktop.
Save aharpole/8925320 to your computer and use it in GitHub Desktop.
CC validation refactoring exercise

You need RSpec installed to run these tests.

gem install rspec
rspec credit_card_spec.rb

The CreditCard class is currently working but the code is in need of some refactoring. Refactor it (ensuring that the specs continue to pass) and when you are finished, share the gist with us.

Feel free to include in your gist a README containing an explanation of your refactorings and any thoughts or philosophies behind what you did. We're particularly interested in understanding what you personally consider to be good code, and this exercise will help us see into that a bit.

class CreditCard
def initialize(ccn)
@ccn = ccn.to_s.split("").each { |string| string.to_i}
@ccn_ints = @ccn.map(&:to_i)
raise ArgumentError, "Invalid credit card number" if @ccn.size != 16
end
def valid?
change_numbers = []
product_sum = []
counter = 1
@ccn_ints.each do |x|
if counter % 2 == 0
change_numbers << (x * 2)
else
change_numbers << x
end
counter += 1
end
change_numbers.each do |element|
if element < 10
product_sum << element
else
product_sum << (element / 10)
product_sum << (element % 10)
end
end
sum = 0
product_sum.each { |a| sum += a }
sum % 10 == 0
end
end
require 'rspec'
require_relative 'credit_card'
describe CreditCard do
describe '#initialize' do
it 'Expects a single argument for the card' do
CreditCard.instance_method(:initialize).arity.should eq 1
end
it 'raises ArgumentError on card > 16' do
expect {
CreditCard.new(11111111111111112)
}.to raise_error(ArgumentError)
end
it 'raises ArgumentError on card < 16' do
expect {
CreditCard.new(1)
}.to raise_error(ArgumentError)
end
end
describe '#valid?' do
it 'expects no arguments to be passed' do
CreditCard.instance_method(:valid?).arity.should be_zero
end
it 'returns true for a valid card' do
card = CreditCard.new(4408041234567893)
card.should be_valid
end
it 'returns false for a bad card' do
card = CreditCard.new(4408041234567892)
card.should_not be_valid
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment