Reputation: 171
New to Crystal-lang, I'm actually trying to code a Caesar cipher. Problem is, when I enter a string to encode, the program show the same string without modification.
if ARGV.size < 3
puts "./caesarcipher [ed] [text] [num]"
exit
end
letter = ARGV[0]
str = ARGV[1]
n = ARGV[2].to_i
alphabet = ("A".."Z").to_a
case letter
when "e" then puts str.tr(alphabet.join, alphabet.rotate(n).join)
when "d" then puts str.tr(alphabet.join, alphabet.rotate(n * -1).join)
else puts "./caesarcipher [ed] [text] [num]"
end
Since the two arguments in the tr method contain what I want and tr must return a value, I don't understand why nothing change.
Upvotes: 2
Views: 77
Reputation: 2203
Welcome to Stack Overflow!
The reason why this didn't work for you, is because if you examine the alphabet
array, it's actually only capital letters. So in your translation, you are only translating the upper case characters. If you instead change
alphabet=("a".."z").to_a
that will translate for the lower case characters.
If you want to do both, then I would suggest creating two "alphabets" one with upper and one with lower case letters, and then applying the translation twice on the string, one with upper and one with lower case alphabets.
Upvotes: 1