0
0

More than 1 year has passed since last update.

Ruby で配列に対して find したアイテムを消していく

Posted at

やりたいこと

配列に対して、特定のアイテムを1つずつ見つけてそのアイテムを配列から消していきたい。Array#delete だと対象に合致するものがすべて削除されてしまうので、 find 的に最初の一件のみを対象に削除したい。

# 候補者
candidates = [
  { name: 'Taro' },
  { name: 'Jiro' },
  { name: 'Saburo' },
  { name: 'Shiro' },
  { name: 'Goro' },
  { name: 'Rokuro' },
  { name: 'Shichiro' },
  { name: 'Hachiro' },
  { name: 'Kuro' },
  { name: 'Juro' },
  ...
]

# 当選者
first_elected = [
  'Shiro',
  'Saburo',
  'Jiro',
  'Juro',
  ...
]

# 追加当選者
second_elected = [
  'Taro',
  'Kuro',
  ...
]

やりかた

Array#find_index しながら Array#slice! していく。(絶対メソッド用意されてると思ってるんだけど見つけられなかった。見落としてるのかな? https://docs.ruby-lang.org/ja/latest/class/Array.html)

first_elected.map { |elected|
  # 候補者を見つけながら候補対象から外す
  candidates
    .find_index { |item| item[:name] == elected }
    .then { |index| index && candidates.slice!(index) }
}

Docs

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