LoginSignup
5
1

More than 1 year has passed since last update.

[Ruby] 配列から特定の要素を 1 つだけ削除する

Last updated at Posted at 2021-09-08

やりたいこと

Array#deleteArray#reject を使って配列から任意の要素を削除する場合、その要素が重複している場合はすべて削除してしまう。

animals = ['🐈', '🐈', '🐕', '🐕', '🐈']
animals.delete('🐕') # destructive
#=> "🐕"
animals
#=> ["🐈", "🐈", "🐈"]

animals = ['🐈', '🐈', '🐕', '🐕', '🐈']
animals.reject { |animal| animal == '🐕' } # not destructive
#=> ["🐈", "🐈", "🐈"]

これを 1 要素のみ削除するようにしたい。

# こうしたい。
["🐈", "🐈", "🐕", "🐈"]

方法

Array#index でインデックス値を取得し、その値を利用して要素を削除する。

animals = ['🐈', '🐈', '🐕', '🐕', '🐈']
animals.delete_at(animals.index('🐕')) # destructive
#=> "🐕"
animals
#=> ["🐈", "🐈", "🐕", "🐈"]

animals = ['🐈', '🐈', '🐕', '🐕', '🐈']
animals.reject.with_index { |_, i| i == animals.index('🐕') } # not destructive
#=> ["🐈", "🐈", "🐕", "🐈"]
5
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
5
1