Skip to content

Instantly share code, notes, and snippets.

@dbryand
Last active December 23, 2015 07:48
Show Gist options
  • Save dbryand/6602855 to your computer and use it in GitHub Desktop.
Save dbryand/6602855 to your computer and use it in GitHub Desktop.
Will's rotx
# 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}"
@dbryand
Copy link
Author

dbryand commented Sep 18, 2013

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:

  • You'll almost never see / need these things in seasoned ruby:
    • semicolon
    • explicit return
  • Decompose your functions so each chunk of logic is its own method
    and can be unit tested.
  • You had a bug where your character array did not include 'z'. Check
    the difference between two periods vs. three:
chars = ('a'..'z').to_a
chars = ('a'...'z').to_a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment