Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 34 / 68

Building a Caesar Cipher (a Character-Shifting Cipher)

In this lesson you will implement the classic Caesar cipher and practise string manipulation using character codes. This is for anyone searching for "Ruby encryption implementation".

The Caesar cipher is a simple cipher from ancient Rome that replaces each letter with the one a fixed number of positions further along the alphabet. It is very simple next to modern cryptography, but it is an ideal exercise for practising character-code arithmetic.

The sample code combines the regular expression .gsub(/[A-Z]/) with a block to shift only the capital letters. The key flow is converting a character to a number (its character code) with .ord, doing the arithmetic, and converting back with .chr.

A common stumbling block for beginners is passing a block to gsub. Normally you give gsub the replacement text, but a block lets you decide the replacement dynamically for each match - a far more flexible use.

Notice how anything that is not a capital letter is passed through unchanged. As a doorway into modern cryptography, it is worth building the mechanism yourself.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)