-2

I'm creating a caesar cipher in Ruby based on the code from Rosetta Code, but my code only prints the original word, rather than the modified word.

Here's my code:

class String
  ALPHABET = ("A".."Z").to_a

  def caesar_cipher(num)
    self.tr(ALPHABET.join, ALPHABET.rotate(num).join)
  end

end

word = gets.chomp.to_s

encypted  = "#{word}".caesar_cipher(8)
decrypted = "#{word}".caesar_cipher(-8)

puts "Encrypt or Decrypt?"

choice = gets.chomp.to_s.downcase

if choice == "encrypt"
  puts encypted
elsif choice == "decrypt"
  puts decrypted
else
  puts "Invalid option"
end

Any help would be greatly appreciated!

  • 1
    Which like is causing the error? Really, with so few lines that can't be hard to determine. It's called debugging, a very important skill. – zaph Apr 04 '18 at 02:37
  • Please, construct a [mcve]. I am pretty sure that you don't require 22 lines to demonstrate your problem. For example, I am willing to bet that `puts` is irrelevant to your question. Also, please give a better description of your problem than "word not changing". What is it that you expect to happen? Why do you expect that to happen? What happens instead? What is the difference? Why is that difference important? – Jörg W Mittag Apr 04 '18 at 06:38

2 Answers2

3

You don't necessarily need to declare a constant ALPHABET but you can if you want. The tr method copies a String object and then it will replace characters in the String with specified characters. As mentioned, you're only saying to check for capital letters and replace those but you're taking a word and making it downcase:

word = gets.chomp.to_s.downcase

You can modify your method like this:

class String

def caeser_cipher(num)
    self.tr('a-z',("a".."z").to_a.rotate(num).join)
end

Now, you get the encrypted string (which you can always convert to upcase if you want):

"hello".caeser_cipher(8)
=> "pmttw"
David E.
  • 61
  • 2
0

Your ALPHABET array only contains uppercase letters, thus your corresponding method only accounts for uppercase letters. You need to update ALPHABET to contain lowercase letters and then your code will work as expected.

Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35