0
0

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 3 years have passed since last update.

【Ruby】文字列を置換するgsubメソッドの使い方

Posted at

プログラミング勉強日記

2021年4月2日

gsubメソッドとは

 文字列を別の文字列に置換するメソッド。正規表現を用いて置換・削除することもできる。
 メソッド名の最後に!(ビックリマーク)を付けて破壊的メソッドを使用することもできる。gsub!メソッドを使うと、置換した文字列を元の文字列に書きかえる。

使い方
# 正規表現を使わない場合
"文字列".gsub("置換したい文字列", "置換後の文字列")
# 正規表現を使う場合
"文字列".gsub(/正規表現/, "正規表現に該当した箇所を置換した後の文字列")

サンプルプログラム

"abcdefg".gsub("def", "aa")
# => "abcaag"

"abcdefg".gsub(/def/, "aa")
# => "abcaag"

"abcabc".gsub(/b/, "<<\&>>")
# => "a<<b>>ca<<b>>c"

参考文献

instance method String#gsub
instance method String#gsub!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?