class ShiftCipher::Caesar
Constants
- DEFAULT_OFFSET
- FIRST_UNICODE_CODEPOINT
- LAST_UNICODE_CODEPOINT
Attributes
offset[RW]
Public Class Methods
new(start = 0)
click to toggle source
# File lib/shift_cipher/caesar.rb, line 10 def initialize(start = 0) @offset = calculate_offset(start) end
Public Instance Methods
decrypt(message)
click to toggle source
# File lib/shift_cipher/caesar.rb, line 18 def decrypt(message) shift(message, -offset) end
encrypt(message)
click to toggle source
# File lib/shift_cipher/caesar.rb, line 14 def encrypt(message) shift(message, offset) end
Private Instance Methods
calculate_offset(character)
click to toggle source
# File lib/shift_cipher/caesar.rb, line 36 def calculate_offset(character) if ("A".."z").include?(character) character.downcase.ord - FIRST_UNICODE_CODEPOINT elsif (0..26).include?(character.to_i.abs) character.to_i else DEFAULT_OFFSET end end
character_for(unicode_codepoint)
click to toggle source
Given the shifted order for a char, returns the corresponding character If the offset takes us past 123 ('z'), we wrap around to 97 ('A')
Returns Char
# File lib/shift_cipher/caesar.rb, line 58 def character_for(unicode_codepoint) if unicode_codepoint < FIRST_UNICODE_CODEPOINT unicode_codepoint = LAST_UNICODE_CODEPOINT - (FIRST_UNICODE_CODEPOINT - unicode_codepoint) elsif unicode_codepoint >= LAST_UNICODE_CODEPOINT unicode_codepoint = FIRST_UNICODE_CODEPOINT + (unicode_codepoint - LAST_UNICODE_CODEPOINT) end unicode_codepoint.chr end
is_alpha?(character)
click to toggle source
# File lib/shift_cipher/caesar.rb, line 46 def is_alpha?(character) character.match(/^[[:alpha:]]$/) end
is_numeric?(character)
click to toggle source
# File lib/shift_cipher/caesar.rb, line 50 def is_numeric?(character) character.match(/^[[:digit:]]$/) end
shift(message, directional_offset)
click to toggle source
# File lib/shift_cipher/caesar.rb, line 24 def shift(message, directional_offset) return unless message message.downcase.split("").map do |character| if is_alpha?(character) character_for(character.ord + directional_offset) elsif is_numeric?(character) character end end.join("").squeeze(" ") end