crypto_square.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Crypto square code for encoding secret messages
class Crypto
  def initialize(text)
    @text = text
  end

  def normalize_plaintext
    # Strip out non-word chars
    @text.downcase.gsub(/[^\w]/, '')
  end

  def size
    # Square size to use
    Math.sqrt(normalize_plaintext.length).ceil
  end

  def plaintext_segments
    # Plain text broken up into correctly sized strings
    plaintext_char_segments.map(&:join)
  end

  def ciphertext
    # Continuous ciphertext
    ciphertext_parts.join
  end

  def normalize_ciphertext
    # Ciphertext broken up into groups
    ciphertext_parts.join(' ')
  end

  private

  def plaintext_char_segments
    # Plain text broken up into correctly sized char arrays
    normalize_plaintext.chars.each_slice(size)
  end

  def ciphertext_parts
    # Ciphertext broken up into separate arrays
    first, *rest = *plaintext_char_segments
    first.zip(*rest).map(&:join)
  end
end

Comments


You're not logged in right now. Please login via GitHub to comment