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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Normalizing and shape-checking input before the real algorithm keeps the core logic clean.
- 2The Luhn checksum doubles every second digit from the right and folds sums over 9 back into a single digit.
- 3Breaking a rule into small named methods makes each numeric step self-documenting.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/validating-credit-card-numbers-with-luhn-explained-ruby-b872/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.