LoginSignup
0
0

More than 3 years have passed since last update.

【Ruby】String#tr メソッドについて覚え書き

Posted at

String#tr メソッド

文字列に含まれる文字の置き換えができる

puts "abcabc".tr("a", "z") 
# =>"zbczbc"

検索する文字は範囲指定もできる

puts "abc".tr('a-z', 'A-Z')  
# => "ABC"

# シーザー暗号(アルファベットを3文字分ずらす)の解読
puts "ORYV".tr("A-Z", "D-ZA-C") 
# => "RUBY"

# 任意の文字数分ずらしたい場合
chars = [*"A".."Z"]
keyword = "RUBY"
encrypted_keyword = keyword.tr(chars.join, chars.rotate(-5).join)
# Array#rotateで任意の分だけ文字をずらせる。
puts encrypted_keyword
# => "MPWT"

参照
https://docs.ruby-lang.org/ja/2.6.0/method/String/i/tr.html
https://docs.ruby-lang.org/ja/2.6.0/method/Array/i/rotate.html
https://docs.ruby-lang.org/ja/latest/method/Array/i/join.html
https://qiita.com/ya-maruchoba/items/9e26c971fbaffb77c7d2

0
0
0

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
0
0