Created
May 15, 2012 14:43
-
-
Save anolson/2702299 to your computer and use it in GitHub Desktop.
Luhn Checksum
This file contains 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 LuhnChecksum | |
attr_accessor :number | |
def initialize(number = "") | |
@number = number | |
end | |
def valid? | |
calculate_checksum % 10 == 0 | |
end | |
def calculate_checksum | |
all_individual_digits.inject(:+) | |
end | |
private | |
def digits | |
number.scan(/\d/).collect{ |c| c.to_i }.to_a.reverse | |
end | |
def all_individual_digits | |
odd + double_digits(even) | |
end | |
def even | |
digits.select.with_index { |digit, index| digit if (index + 1).even? } | |
end | |
def odd | |
digits.select.with_index { |digit, index| digit if (index + 1).odd? } | |
end | |
def double_digits(array = []) | |
array.collect { |digit| individual_digits(digit * 2) }.flatten | |
end | |
def individual_digits(digit) | |
digit.to_s.scan(/\d/).collect { |i| i.to_i } | |
end | |
end |
This file contains 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
require "rspec" | |
require "./luhn_checksum" | |
describe LuhnChecksum do | |
it "initializes a new object with a string of numbers" do | |
checksum = LuhnChecksum.new | |
checksum.number.should eq "" | |
checksum = LuhnChecksum.new("79927398719") | |
checksum.number.should eq "79927398719" | |
end | |
it "calculates the checksum" do | |
checksum = LuhnChecksum.new("79927398713") | |
checksum.calculate_checksum.should eq 70 | |
end | |
it "correctly validates the checksum" do | |
LuhnChecksum.new("79927398710").valid?.should be_false | |
LuhnChecksum.new("79927398711").valid?.should be_false | |
LuhnChecksum.new("79927398712").valid?.should be_false | |
LuhnChecksum.new("79927398713").valid?.should be_true | |
LuhnChecksum.new("79927398714").valid?.should be_false | |
LuhnChecksum.new("79927398715").valid?.should be_false | |
LuhnChecksum.new("79927398716").valid?.should be_false | |
LuhnChecksum.new("79927398717").valid?.should be_false | |
LuhnChecksum.new("79927398718").valid?.should be_false | |
LuhnChecksum.new("79927398719").valid?.should be_false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment