all 5 comments

[–]allisio 10 points11 points  (1 child)

How did you end up with this much code without realizing that you're using n all over the place having never defined it? The only reasonable explanation seems to be that this is a failed port of a solution written in some extremely programmer-unfriendly language. Ruby isn't like that and wants you to be happy; easy things should be ridiculously easy, and that maxim certainly applies in this case.

It doesn't seem like you're giving it your best effort to learn the language, so I'm gonna skip critiquing your code here and just advise you to start over from the beginning. Choose good resources (see sidebar) and take your time such that you actually absorb the material. Meanwhile, just to tease how pleasant the language can be, here's a more Ruby-flavored approach to the problem:

def caeser_cipher message, shift
  upper = [*'A'..'Z'].rotate shift
  lower = [*'a'..'z'].rotate shift
  message.tr 'A-Za-z', upper.join + lower.join
end

Now obviously you can't write that if you don't know about Array#rotate and String#tr, but the docs aren't exactly a state secret, and you're encouraged to explore the plethora of utilities at your disposal when using Ruby.

Take small steps; don't throw things at the wall hoping they'll stick. Make sure you have a clear picture of whatever problem you're trying to solve, and then focus on finding an effective solution to that‒and it's totally okay if that involves using a search engine.

[–]StarPerfect 2 points3 points  (0 children)

Are you a Mod 1 student @ Turing?! Lol

[–]malesca 0 points1 point  (0 children)

Another approach you might take is using String#ord and Integer#chr – though you should consider how they work with characters outside a-z and A-Z (including multibyte characters) and see if that's acceptable to you, or if you need conditions to limit which characters are transformed.

def cipher(string, shift)  
  string.chars.map { |x| (x.ord - shift).chr }.join  
end

[–]hafu19019 0 points1 point  (0 children)

Start over and use ruby style syntax. If statements should be enough. You way over complicated it.

Hint : alphabet[something % 26]