LoginSignup
5
5

More than 5 years have passed since last update.

配列の指定した値と一致する要素のindexを全て配列で返すメソッド

Last updated at Posted at 2015-06-27
arr1 = [100, 200, 100, 300, 100, 400]
arr2 = ["ととろ", "まっくろくろすけ", "ととろ", "めいちゃん", "さつきちゃん", "ととろ"]

な配列があったとする。
指定した値と一致する要素のindexを全て配列で返す

arr1.where_is(100)
=> [0, 2, 4]
arr2.where_is("ととろ")
=> [0, 2, 5]

なメソッドが欲しかったから作った。

class Array
  def where_is(value)
    self.map.with_index{|item, i| i if item == value}.compact!
  end
end

追記

配列の指定した文字列と部分一致する要素のindexを全て配列で返すメソッド - Qiitaコメントで教えていただいた@pocariさんのRuby - find_allのindex版 - Qiitaのほうが柔軟で汎用的なので今後はこちらを使うことにします。
ありがとうございます。

5
5
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
5