LoginSignup
0
0

More than 1 year has passed since last update.

Ruby 配列を検索して置き換えまたは削除

Posted at

方法

[1] 文字列"hoge"を"hogehoge"に置き換える

array = ["huga","hoga","hoge"]

# arrayから"hoge"を検索して"hogehoge"で置換
array.map!{|x| x=="hoge" ? "hogehoge" : x}

p array
# 出力結果=> ["huga","hoga","hogehoge"]

[2] 文字列"hoge"を"hogehoge"に置き換える(非推奨)

array = ["huga","hoga","hoge"]

# arrayから"hoge"を検索して"hogehoge"で変換
array[array.index("hoge")] = "hogehoge"

puts array
# 出力結果=> ["huga","hoga","hogehoge"]

こちらの方法は検索する文字列がない場合このようなエラーが出る。
10272050481bd11c4015d899de61beda.png

[3] 数値0だけを削除する

array = [0, 0, 4, 5, 0 ,0]

# arrayから0を削除
array.delete_if { |num|
  num == 0
}

p array
# 出力結果=> [4, 5]

まとめ

paizaのスキルチェックでよく検索する配列の操作についてまとめました

0
0
1

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