-
-
Save Sutto/742975 to your computer and use it in GitHub Desktop.
Revisions
-
Sutto revised this gist
Dec 16, 2010 . 1 changed file with 26 additions and 15 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -1,19 +1,30 @@ def luhn_valid?(number) return unless number.is_a?(String) # Convert to a reversed list of digits digits = number.scan(/\d/).map(&:to_i).reverse # No numbers in the string return false if digits.empty? check_digit = digits.shift # For each of the normal integers, compute the correct sum final_digits = [] digits.each_with_index do |value, index| # Second from the left is double. if index.even? final_digits << (value * 2).to_s.split('').map(&:to_i) else final_digits << value end end # Actually compute the product, including check digit. (final_digits.flatten.inject(:+) + check_digit) % 10 == 0 end puts "#{luhn_valid?('4111 1111 1111 1111')} should be true" puts "#{luhn_valid?('5500 0000 0000 0004')} should be true" puts "#{luhn_valid?('3400 0000 0000 009')} should be true" puts "#{luhn_valid?('3000 0000 0000 04')} should be true" puts "#{luhn_valid?('3000 0000 0000 04')} should be true" puts "#{luhn_valid?('6011 0000 0000 0004')} should be true" puts "#{luhn_valid?('2014 0000 0000 009')} should be true" puts "#{luhn_valid?('3088 0000 0000 0009')} should be true" puts "#{luhn_valid?('3088 0000 0000 0008')} should be false" -
thomasfedb created this gist
Dec 16, 2010 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,19 @@ def luhn_valid?(value) return false unless value.is_a?(String) && !value.strip.empty? value.gsub!(/\D/, '') sum = 0 value.split(//).each_with_index do |number, index| if index.even? sum += (number * 2).to_s.split(//).map(&:to_i).sum else sum += number end end sum % 10 == 0 end