Skip to content

Instantly share code, notes, and snippets.

@broguinn
Created August 30, 2013 00:58
Show Gist options
  • Save broguinn/6385235 to your computer and use it in GitHub Desktop.
Save broguinn/6385235 to your computer and use it in GitHub Desktop.
luhn
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
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