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.

gsubとgsub!(Ruby)

Last updated at Posted at 2019-11-14

gsubメソッドを使用してみました。
置換をしてくれるメソッドです。

string1 = "seven"
puts string2 = string1.gsub(/seven/, 'eleven') # => eleven
puts string1 # => seven
puts string2 # => eleven

次にgsub!としてみた場合レシーバを置換したものに完全に置き換えました。

string1 = "seven"
puts string2 = string1.gsub!(/seven/, 'eleven') # => eleven
puts string1 # => eleven
puts string2 # => eleven

次に置換に対応する文字列がなかった場合です。
置き換えるものがないとレシーバに変化は無いです。

string1 = "seven"
puts string2 = string1.gsub(/a/, 'eleven') # => seven
puts string1 # => seven
puts string2 # => seven

置換に対応する文字列がなく!を使った場合です。
返り値はnilになります。

string1 = "seven"
puts string2 = string1.gsub!(/a/, 'eleven') # => nil
puts string1 # => seven
puts string2 # => nil

レシーバと返り値の関係を意識できるように記述しました。

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?