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

任意の文字列を削除する

Posted at

任意の文字列に対してn番目の文字を消し、
その消した文字列を出力するメソッドを作成したいと思います。

メソッドのの呼び出し方は、

missing_char(string, num)

で呼び出したいと思います。
出力例としては、

missing_char('kitten', 1)
 => itten
missing_char('kitten', 2)
 => ktten
missing_char('kitten', 4)
 =>kiten

このように出力したいと考えています。

sliceメソッドを使用すると配列や文字列から指定した要素を取り出すことができます。
例)

string = "hoge"

str = string.slice(1)

# strに代入した文字列を出力
puts str
# =>"o"

# sliceメソッドでは文字列は元のまま出力される
puts string
# =>"hoge"

sliceメソッドを使用して、記述していきます。

初めにmissing_charメソッドを作成します。その仮引数に(string, num)を設定します。

def missing_char(string, num)
  string.slice(num - 1)
  puts string
# stringに"hoge", numに2が渡されているが、元の文字列は変化しない
# =>hoge
end

この記述では、任意の文字列から指定した要素は取り出すことはできますが、文字列を出力しても、変化はありません。

そこでslice!メソッドを使用します。slice!メソッドは元の配列や文字列を変化させるメソッドです。
Ruby 3.0.0 リファレンスマニュアル, slice!
例)

string = "hoge"
str = string.slice!(1)
puts str

# =>"o"

puts string
# =>"hge"
# "o"が取り除かれる

このメソッドを使用すると、

def missing_char(string, num)
  string.slice!(num - 1)
  puts string
end

元の文字列が変化して出力されるようになりました。

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