Here is an example of a Caesar cipher function implemented in Ruby:
main.rb490 chars23 lines
The caesar_cipher
function takes in two parameters: text
- the string to be encrypted, and shift
- the number of positions each character should be shifted in the alphabet.
The function iterates through each character in the text. If the character is a letter (lowercase or uppercase), it calculates the new character by subtracting the ASCII offset of 'a' or 'A' (depending on the case), applying the shift, and wrapping around if necessary. The new character is then concatenated to the encrypted_text
string. If the character is not a letter, it is directly concatenated to the encrypted_text
.
Finally, the function returns the encrypted text.
In the example usage, the text "Hello, World!" is encrypted with a shift of 5, resulting in the encrypted text "Mjqqt, Btwqi!".
gistlibby LogSnag