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】文字列末尾への挿入、置換、破壊【b021】

Last updated at Posted at 2020-10-21

某スキルチェックの際にググったメソッド忘備録 兼 初投稿

1.出力された値の取得

ループ処理の中に任意の数、入力された文字を配列として取得
qiita.rb
hoge  #入力される文字
huga  #入力される文字
piga  #入力される文字

lines = []  #予め配列の変数を定義
lines << gets.chomp  #改行がないようにchomp

・複数行にわたって文字列がくるので配列に追加していく

qiita.rb
lines = ["hoge", "fuga", "piga"]
puts lines[0]  #インデックス番号(添字)を指定して任意の文字を出力
>> hoge

・インデックス番号で任意の文字を呼び出し条件によって必要な変更を行い出力

2.文字末尾へ挿入

文字列末尾の種類によって挿入するか置換するかの条件分岐を考えます。
qiita.rb
#条件分岐
文字列.end_with?('探したい値')  #任意の文字末尾に探したい値があるか
puts hoge.end_with?('e', 'ge', 'ch')  #複数の値を一度に参照可能(どれか一つでもあればおk)
>> ture

#挿入メソッド
文字列.insert(挿入先のインデックス番号,"挿入する値") 
#['h','o','g','e']のインデックス番号は先頭からだと[0,1,2,3]、末尾からだと[-4,-3,-2,-1]
puts hoge.insert(-1,"s")  #末尾へ挿入
>> hoges

puts hoge.insert(0,"s")  #先頭へ挿入
>> shoge

#破壊的メソッド
文字列.delete_suffix("消す値")  #末尾の消す値を消去
puts gehoge.delete_suffix("ge")
>> geho  #先頭は消えない

#置換(末尾"ge"を"ver"へ変換)
puts gehoge.delete_suffix("ge").insert(-1,"ver")
>> hehover

参考
https://qiita.com/uuchan/items/a4e9382440bdc4d2ac75
https://qiita.com/prgseek/items/92b49fe6b0a579f9cdd8

さくっと置換できれば良かったが難しかったので合わせ技でゴリ押した
もっと良い方法を知っている方、コメントいただければ幸いです!

0
0
2

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?