create a caesar cipher function in ruby

Here is an example of a Caesar cipher function implemented in Ruby:

main.rb
def caesar_cipher(text, shift)
  encrypted_text = ''
  
  text.each_char do |c|
    if c.match(/[a-zA-Z]/)
      ascii_offset = c.downcase == c ? 'a'.ord : 'A'.ord
      encrypted_char = (((c.ord - ascii_offset) + shift) % 26 + ascii_offset).chr
      encrypted_text.concat(encrypted_char)
    else
      encrypted_text.concat(c)
    end
  end
  
  return encrypted_text
end

# Example usage
text = "Hello, World!"
shift = 5

encrypted_text = caesar_cipher(text, shift)
puts encrypted_text
490 chars
23 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!".

related categories

gistlibby LogSnag