From: Todd Benson Date: 2008-03-17T19:32:47+09:00 Subject: Re: Cipher On Mon, Mar 17, 2008 at 5:21 AM, Todd Benson wrote: > On Sun, Mar 16, 2008 at 9:00 PM, Todd Benson wrote: > > > > > On Sun, Mar 16, 2008 at 7:50 PM, Max Zhou wrote: > > > I am trying to make a program that takes what you input, and encrypts it by turning a to p, b to q, z to b, etc. It moves the letter 2 spaces to the left (a to c) and moves it down (c to p). (See below.) Even though you can just say that a will be n, how do you seperate each letter and turn it into a string? Please put it in terms that a Ruby beginner would understand. > > > abcdefghijklm > > > nopqrstuvwxyz > > > > > > > > > > > > --------------------------------- > > Just for fun, I revisited this. To include the printable characters > on an english-based system (ASCII codes 32 through 126), not including > tab, return, line-feed, etc... > > > puts str = "Hello, world! Yabba dabba doo!" > puts > > char_set = (32..126).map.pack('c*') > start, finish, offset = ?a, ?p, ?p - ?a > puts "char_set:\n" + char_set = (?\s..?~).map.pack('c*') > puts > > size = char_set.size > new_str = "" > str.each_byte do |byte| > new_str << char_set[(byte + offset - char_set[0]) % size] > end > puts "enciphered: \n" + new_str Dang it! Another thing that unit tests won't catch: code that is redundant! Removing the first "char_set =" line will have the same result... puts str = "Hello, world! Yabba dabba doo!" puts start, finish, offset = ?a, ?p, ?p - ?a puts "char_set:\n" + char_set = (?\s..?~).map.pack('c*') puts size = char_set.size new_str = "" str.each_byte do |byte| new_str << char_set[(byte + offset - char_set[0]) % size] end puts "enciphered: \n" + new_str Todd