Class: Ciphers::Caesar
- Inherits:
-
Object
- Object
- Ciphers::Caesar
- Defined in:
- lib/crypto-toolbox/ciphers/caesar.rb
Class Method Summary collapse
Instance Method Summary collapse
- #decipher(message, shift) ⇒ Object
-
#encipher(message, shift) ⇒ Object
Within encipher and decipher we use a regexp comparision.
Class Method Details
Instance Method Details
#decipher(message, shift) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/crypto-toolbox/ciphers/caesar.rb', line 39 def decipher(,shift) assert_valid_shift!(shift) real_shift = convert_shift(shift) .split("").map do |char| mod = (char =~ /[a-z]/) ? 123 : 91 offset = (char =~ /[a-z]/) ? 97 : 65 # first reduce by 65 to map A to 0 ; then mod-sub with "A"(91)-65; and re-add the 65 to convert back to real ascii A value (char =~ /[^a-zA-Z]/) ? char : CryptBuffer(char).sub(offset).mod_sub(real_shift,mod: mod-offset).add(offset).str end.join end |
#encipher(message, shift) ⇒ Object
Within encipher and decipher we use a regexp comparision. Array lookups are must slower and byte comparision is a little faster, but much more complicated
Alphabet letter lookup algorithm comparision:
Comparison: (see benchmarks/string_comparision.rb) string.bytes.first == A : 3289762.7 i/s string =~ [A-Za-Z] : 2010285.8 i/s - 1.64x slower Letter Array include?(A): 76997.0 i/s - 42.73x slower
27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/crypto-toolbox/ciphers/caesar.rb', line 27 def encipher(,shift) assert_valid_shift!(shift) real_shift = convert_shift(shift) .split("").map do|char| mod = (char =~ /[a-z]/) ? 123 : 91 offset = (char =~ /[a-z]/) ? 97 : 65 (char =~ /[^a-zA-Z]/) ? char : CryptBuffer(char).add(real_shift, mod: mod, offset: offset).str end.join end |