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
typescript
import { Injectable, PipeTransform, ArgumentMetadata,
A custom validation pipe in NestJS
validation
dto
recursion
Intermediate
10 steps
go
package handlers type ListFilters struct { Status string `form:"status" binding:"omitempty,oneof=active archived all"`
Cross-field query validation in Gin
validation
struct-tags
query-binding
Intermediate
9 steps
ruby
class UserColor GOLDEN_RATIO_CONJUGATE = 0.618033988749895 def initialize(username)
Deriving a stable color from a username
hashing
color-theory
deterministic-mapping
Intermediate
7 steps
ruby
namespace :counter_cache do desc "Recalculate comments_count for posts after a backfill" task warm_post_comments: :environment do scope = Post.where(comments_count: nil).or(Post.where("comments_count < 0"))
Backfilling counter caches in a Rake task in Rails
counter-cache
batching
rake-tasks
Intermediate
6 steps
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 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.