Ceasars Cipher in Ruby -
class ceasarscipher def initialize text @text = text.split '' end def encrypt key @text = @text.each |letter| key.times if letter != "z" letter.next! else letter = "a" end end end end def printcipher puts @text end end cipher = ceasarscipher.new "abcdefghijklmnopqrstuvwxyz" cipher.encrypt 2 cipher.printcipher
when run code output is: c d e f g h j k l m n o p q r s t u v w x y z z z
i don't understand why there z 3 times. thought long time don't it... answers.
it's because when letter = "a"
don't change string, instead declare new variable.
here fix using map
:
def encrypt key @text.map! |l| key.times.reduce(l) |l| l == 'z' ? 'a' : l.next end end end
Comments
Post a Comment