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

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -