3
1

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.

trメソッドとは?(Ruby)

Last updated at Posted at 2019-06-29

trメソッドとは、第一引数を第二引数に変換するメソッド。
つまり、既存の文字を新しく違う文字に変換したい場合に便利となるメソッド

例えば、指定の文字列を小文字から大文字に変換した場合がこちら

sample.rb
string = "abcde"
puts string.tr("a-z", "A-Z")

 #結果 => ABCDE

ROT13のような形で、文字をずらしたい場合はこちら

sample.rb
string = "abcde"
puts string.tr("a-zA-Z", "n-za-mN-ZA-M")
 #結果 => nopqr

ちなみに、一部の文字の変換も可能!

sample.rb
string = "abcde"
puts string.tr("bc", "BC")
# 結果 => aBCde

まだまだ勉強中なので、追記や違っているところ等ありましたら、コメントいただけると嬉しいです!

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?