Created
August 16, 2012 06:38
-
-
Save JohnB/3367413 to your computer and use it in GitHub Desktop.
Ruby LUN checker
This file contains hidden or 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
# each_with_index is useful, so why not inject_with_index? | |
module Enumerable | |
def inject_with_index(memo) | |
each_with_index {|obj, idx| memo = yield(memo, obj, idx)} | |
memo | |
end | |
end | |
def passes_lun?(cardnum) | |
digits = cardnum.gsub(/\D/,'').reverse.split('').map(&:to_i) | |
digits.inject_with_index(0) do |memo, digit, idx| | |
memo += (idx.even?) ? digit : ((digit*2 > 9) ? (digit*2 - 9) : (digit*2)) | |
end % 10 == 0 | |
end | |
# Examples from http://en.wikipedia.org/wiki/Luhn_algorithm | |
# 79927398713 should pass the test, as should 16 "8"s | |
("79927398710".."79927398719").each {|num| puts "#{num}: #{passes_lun?(num)}" } | |
puts passes_lun?("79927398713") | |
puts passes_lun?("8888888888888888") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment