12
2

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] Array#find_index の複数の index を返すバージョンがほしい

Last updated at Posted at 2020-01-24

バージョン情報

$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-darwin18]

やりたいこと

Array#find_index は引数に一致する最初の要素のインデックスを返す。

%w(🦜 🐟 🐁 🦄 🐁).find_index('🐁') #=> 2

でも一致するすべてのインデックスを返してほしいな。

%w(🦜 🐟 🐁 🦄 🐁).some_method('🐁') #=> [2, 4]

方法

module ArrayExtension
  refine Array do
    def find_indexes(val)
      filter_map.with_index { |element, i| i if element == val }

      # Ruby 2.7 未満の場合は Enumerable#filter_map がないので他の書き方で。
      # map.with_index { |element, i| i if element == val }.compact
    end
  end
end

using(ArrayExtension) # irb --context-mode=1 で起動すると irb でも using が使えるぞ。

%w(🦜 🐟 🐁 🦄 🐁).find_indexes('🐁') #=> [2, 4]
%w(🦜 🐟 🐁 🦄 🐁).find_indexes('🐟') #=> [1]
%w(🦜 🐟 🐁 🦄 🐁).find_indexes('🐝') #=> []
12
2
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
12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?