Created
August 30, 2013 00:58
-
-
Save broguinn/6385235 to your computer and use it in GitHub Desktop.
luhn
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
def luhn(id, check=0) | |
id = id.to_s.split("").reverse.each_with_index.map do |digit, index| | |
digit = digit.to_i | |
if (index + 1) % 2 == 0 | |
if digit * 2 > 9 | |
(digit * 2) - 9 | |
else | |
digit * 2 | |
end | |
else | |
digit | |
end | |
end | |
id = id.inject{ |total, num| total + num } | |
puts id | |
((id + check) % 10 == 0) ? true : false | |
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' | |
describe 'luhn' do | |
it 'checks if a number passes the luhn algorithm' do | |
luhn(8763).should be_true | |
luhn(1111).should be_false | |
luhn(4473_0504_0429_1622).should be_true | |
end | |
it 'checks against a passed check number' do | |
luhn(1111, 4).should be_true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment