On Sun, Mar 16, 2008 at 7:50 PM, Max Zhou <ball908765 / yahoo.com> 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
>
>
>
>  ---------------------------------
>  Never miss a thing.   Make Yahoo your homepage.

There are many ways to do it, but if it was all lower case, I would probably...

a = "abcdefghijklmnopqrstuvwxyz"
ascii_offset = 15 - 97
str = "antidisestablishmentarianism"
str.each_byte {|b| new_str << a[(b + ascii_offset) % a.size]}
puts new_str

The 15 is to turn a into a p (?p - ?a == 15).  The minus 97 part is to
make sure we work in the ascii byte code range.  each_byte runs
through each byte of the string, where, in the block, the offset is
added and the mod by the size of a (26) to keep the index of a within
the correct bounds.  a[] selects a byte to be appended (<<) to
new_str.

You could wrap this in a method or make it part of String class.
Ideally, I think a person would really want to include the full 256
character set to deal with punctuation and spaces.

Todd