-2

I'm building a basic encryptor that is outputting into an array and not a string. I'm guessing I need to use the .join method but for the life of me can't find out where, without getting an error.

class Encryptor
  def cipher
    {'a' => 'n', 'b' => 'o', 'c' => 'p', 'd' => 'q',
     'e' => 'r', 'f' => 's', 'g' => 't', 'h' => 'u',
     'i' => 'v', 'j' => 'w', 'k' => 'x', 'l' => 'y',
     'm' => 'z', 'n' => 'a', 'o' => 'b', 'p' => 'c',
     'q' => 'd', 'r' => 'e', 's' => 'f', 't' => 'g',
     'u' => 'h', 'v' => 'i', 'w' => 'j', 'x' => 'k',
     'y' => 'l', 'z' => 'm'}
   end

   def encrypt_letter(letter)
     lowercase_letter = letter.downcase
   end

   def encrypt(string)
     letters = string.split("")

     letters.collect do |letter|
       encrypted_letter = encrypt_letter(letter)
     end
   end

end
4

2 回答 2

2

You could tighten up your encrypt_letter method by remembering that the last value evaluated in the method is also the return value.

def encrypt_letter(letter)
  cipher[letter.downcase]
end

Encryptor.new.encrypt_letter('h') #=> "u"

Also, the collect method will actually return an array of all the values returned by the block (the last value evaluated by the block) so there's no need to assign it to a variable within the block. Since you have the array from collect (which is just all the encrypted letters, call join on that (and since that is the final evaluation in the method, it is the return value).

def encrypt(string)
  letters = string.split("")

  letters.collect {|letter| encrypt_letter(letter) }.join
end

Encryptor.new.encrypt("Hello") #=> "uryyb"

Technically, you could even just remove the letters variable and do it all in one line but I personally think it is a little more readable this way.

IMHO:

You could probably make all of the methods class methods since you aren't storing any instance variables and there doesn't seem to be any reason to keep it around outside of just encrypting a string.

于 2013-07-22T13:53:07.633 回答
1
class Encryptor
   def cipher
     {'a' => 'n', 'b' => 'o', 'c' => 'p', 'd' => 'q',
      'e' => 'r', 'f' => 's', 'g' => 't', 'h' => 'u',
      'i' => 'v', 'j' => 'w', 'k' => 'x', 'l' => 'y',
      'm' => 'z', 'n' => 'a', 'o' => 'b', 'p' => 'c',
      'q' => 'd', 'r' => 'e', 's' => 'f', 't' => 'g',
      'u' => 'h', 'v' => 'i', 'w' => 'j', 'x' => 'k',
      'y' => 'l', 'z' => 'm'}
   end

   def encrypt_letter(letter)
     lowercase_letter = cipher[letter.downcase] #each letter passed is crypted here
   end

  def encrypt(string)
    letters = string.split("")

    encrypted_letter = []  #define an array to store each encrypted char

    letters.collect do |letter|          
      encrypted_letter << encrypt_letter(letter) #accumulate encrypted chars in the array
    end
    encrypted_letter.join #now time to use join to form a string and return it
  end
end

Encryptor.new.encrypt("something") #=> "fbzrguvat"
于 2013-07-22T13:44:05.090 回答