-
-
Save jfarmer/5d6e5510bfaefc0b6347 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def rot_n_char(char, rot_by) | |
fail ArgumentError, "First argument must be a 1-letter String (got `#{char}')" unless char.length == 1 | |
case char | |
when ('a'..'z') | |
((char.ord - 'a'.ord + rot_by) % 26 + 'a'.ord).chr | |
when ('A'..'Z') | |
((char.ord - 'A'.ord + rot_by) % 26 + 'A'.ord).chr | |
else | |
char | |
end | |
end | |
def rot_n(string, rot_by) | |
string.chars.map { |char| rot_n_char(char, rot_by) }.join | |
end | |
if __FILE__ == $0 | |
p rot_n("The quick brown fox jumps over the lazy dog.", 14) == "Hvs eiwqy pfckb tcl xiadg cjsf hvs zonm rcu." | |
%w(abcdef bcdefg cdefgh defghi).each_with_index do |output_str, i| | |
input_str = "abcdef" | |
p rot_n(input_str, i) == output_str | |
p rot_n(input_str.upcase, i) == output_str.upcase | |
p rot_n(input_str + input_str.upcase, i) == output_str + output_str.upcase | |
end | |
end |
This file contains hidden or 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
def rot_n(string, n) | |
rotn_ary = [] | |
n = n % 26 | |
n > 13 ? n2 = (26 - n) : n2 = n # n2 for numbers greater than 13 | |
string.each_char do |char| | |
if char.ord < 65 || (char.ord > 90 && char.ord < 97) || char.ord > 122 | |
rotn_ary.push(char) | |
elsif "z".ord - n >= char.downcase.ord && "z".ord - char.downcase.ord + n >= 26 | |
rotn_ary.push((char.ord + n).chr) | |
else | |
rotn_ary.push((char.ord - n2).chr) | |
end | |
end | |
rotn_ary.join | |
end | |
if __FILE__ == $0 | |
p rot_n("People who eat beef are the enemy of vegetarians.", 22) | |
p rot_n("The quick brown fox jumps over the lazy dog.", 14) == "Hvs eiwqy pfckb tcl xiadg cjsf hvs zonm rcu." | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment