ruby 26 lines · 6 steps

Validating credit card numbers with Luhn

A Ruby module that sanitizes a card number, checks its shape, and runs the Luhn checksum.

Explained by highlit
1module CreditCard
2 module_function
3 
4 def valid?(number)
5 digits = number.to_s.gsub(/[\s-]/, "")
6 return false unless digits.match?(/\A\d{13,19}\z/)
7 
8 luhn_valid?(digits)
9 end
10 
11 def luhn_valid?(digits)
12 sum = digits
13 .chars
14 .map(&:to_i)
15 .reverse
16 .each_with_index
17 .sum { |digit, index| index.odd? ? double(digit) : digit }
18 
19 (sum % 10).zero?
20 end
21 
22 def double(digit)
23 doubled = digit * 2
24 doubled > 9 ? doubled - 9 : doubled
25 end
26end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Normalizing and shape-checking input before the real algorithm keeps the core logic clean.
  2. 2The Luhn checksum doubles every second digit from the right and folds sums over 9 back into a single digit.
  3. 3Breaking a rule into small named methods makes each numeric step self-documenting.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Validating credit card numbers with Luhn — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code