faby v faby v - 3 years ago 127
Ruby Question

ruby ceaser cipher printing error, printing unmodified string

I've been having trouble with this ceaser cipher project. I've looked around and compared and have applied my findings but no success yet.

It's got the data but it's just printing out my string without shifting it.

Here's my code at the moment.

def ceaser(k, v = 1)
char = k.split("")
alphabet = Array("a".."z")
cipher = Hash[alphabet.zip(alphabet.rotate(v))]
char.join
end

p ceaser "this string",2


how do I fix it and make it shift?

Answer Source

You are not applying the cipher to the string/array. I iterate through the string and get the mapping of the cipher, push those mappings and then re-join the string.

def ceaser(k, v = 1)
    char = k.split("")
    alphabet = Array("a".."z")
    cipher = Hash[alphabet.zip(alphabet.rotate(v))]
    ciphertext = []

    char.each do |element|
      ciphertext.push(cipher[element])
      #note you do not have anything in the cipher for spaces and it returns nil
    end

    ciphertext.join
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download