7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyで暗号化、復号化

Posted at

 アルゴリズムの本を読んでいて、文字列をポケベルの数字列で暗号化、またポケベルの数字列から文字列に復号化する、というものが載っていたので自分で、コードを書いてみました。
 ハッシュの値からキーを求めるメソッドを使ったことがなかったので、勉強になりました。
 濁点、半濁点は全角で別に打つ必要があることも、ポケベルを使ったことのない自分は知りませんでした。
 これからも簡単なものでも気が向いたらコードを書いていこうと思っています。
 またよりよい方法があったら指摘、お願いします。
 簡単なコードですので解説は省略します。

pocketbell.rb
# -*- coding: utf-8 -*-

class PocketBell
  def initialize
    @table = {
      "あ" => "11", "い" => "12", "う" => "13", "え" => "14", "お" => "15",
      "か" => "21", "き" => "22", "く" => "23", "け" => "24", "こ" => "25",
      "さ" => "31", "し" => "32", "す" => "33", "せ" => "34", "そ" => "35",
      "た" => "41", "ち" => "42", "つ" => "43", "て" => "44", "と" => "45",
      "な" => "51", "に" => "52", "ぬ" => "53", "ね" => "54", "の" => "55",
      "は" => "61", "ひ" => "62", "ふ" => "63", "へ" => "64", "ほ" => "65",
      "ま" => "71", "み" => "72", "む" => "73", "め" => "74", "も" => "75",
      "や" => "81", "(" => "82", "ゆ" => "83", ")" => "84", "よ" => "85",
      "ら" => "91", "り" => "92", "る" => "93", "れ" => "94", "ろ" => "95",
      "わ" => "01", "を" => "02", "ん" => "03", "゛" => "04", "゜" => "05",
    }
  end

  def encryption(string)
    string.split(//).each do |char|
      puts @table[char]
    end
  end

  def decryption(string)
    string.scan(/\d\d/).each do |char|
      puts @table.key(char)
    end
  end
end

pocket_bell = PocketBell.new

pocket_bell.encryption("あいうえお")
puts
pocket_bell.decryption("1112131415")
puts
pocket_bell.encryption("あんこ゛う")

# >> 11
# >> 12
# >> 13
# >> 14
# >> 15
# >> 
# >> あ
# >> い
# >> う
# >> え
# >> お
# >> 
# >> 11
# >> 03
# >> 25
# >> 04
# >> 13
7
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?