Last active
December 23, 2015 07:48
-
-
Save dbryand/6602855 to your computer and use it in GitHub Desktop.
Will's rotx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Build a hash of keys to use for lookup. | |
def build_key(x, encrypt=true) | |
chars = ('a'..'z').to_a | |
{}.tap do |key| | |
chars.each_with_index do |char, idx| | |
if(encrypt) | |
key[char] = chars[(idx + x) % 26] # rotate x clicks forward | |
else | |
key[char] = chars[(idx - x) % 26] # rotate x clicks backwards | |
end | |
end | |
end | |
end | |
# Rotate character using the key we built. | |
def rot_character(char, key) | |
if char.match(/[a-z]/i) | |
lookup = key[char.downcase] | |
char == char.upcase ? lookup.upcase : lookup | |
else | |
char | |
end | |
end | |
def rotx(x, string, encrypt=true) | |
key = build_key(x, encrypt) | |
string.split("").map do |char| | |
rot_character(char, key) | |
end.join | |
end | |
# Test Drive | |
puts "rotx(10, 'Hello, World') = #{rotx 10, 'Hello, World'}" | |
puts "rotx(36, 'Hello, World') = #{rotx 36, 'Hello, World'}" | |
puts "rotx(10, 'Rovvy, Gybvn', false) = #{rotx 10, 'Rovvy, Gybvn', false}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Overall, I think you did a nice job. Clean and good logic. One bug that I found which would have been exposed if you had the letter "p" in your test case. If I'm a critic, I would just say that I can tell this is not written by someone with a lot of ruby experience (meaning you haven't worked on big experienced ruby codebases) but has solid fundamentals.
A couple pieces of feedback:
and can be unit tested.
the difference between two periods vs. three: