Module: HCeasarCipher

Defined in:
lib/h_ceasar_cipher.rb,
lib/h_ceasar_cipher/version.rb

Overview

シーザー暗号モジュール

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.alphabet_only?(text) ⇒ Boolean

バリデーション引数がアルファベットのみかどうかを判定する

Parameters:

  • text (String)

    文字列

Returns:

  • (Boolean)

    アルファベットのみかどうか



49
50
51
# File 'lib/h_ceasar_cipher.rb', line 49

def self.alphabet_only?(text)
  text.match?(/\A[a-zA-Z]+\z/)
end

.decrypt(cipher_text, shift) ⇒ String

復号化引数として、暗号文とシフト数を受け取り、平文を返す

Parameters:

  • cipher_text (String)

    暗号文

  • shift (Integer)

    シフト数

Returns:

  • (String)

    平文



31
32
33
# File 'lib/h_ceasar_cipher.rb', line 31

def self.decrypt(cipher_text, shift)
  encrypt(cipher_text, -shift)
end

.encrypt(plain_text, shift) ⇒ String

暗号化引数として、平文とシフト数を受け取り、暗号文を返す

Parameters:

  • plain_text (String)

    平文

  • shift (Integer)

    シフト数

Returns:

  • (String)

    暗号文



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/h_ceasar_cipher.rb', line 14

def self.encrypt(plain_text, shift)
  plain_text.chars.map do |char|
    if char.match?(/[a-z]/)
      ((char.ord - 97 + shift) % 26 + 97).chr
    elsif char.match?(/[A-Z]/)
      ((char.ord - 65 + shift) % 26 + 65).chr
    else
      char
    end
  end.join
end