summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-enum-ext/mrblib/enum.rb
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2014-03-25 16:27:10 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2014-03-25 16:27:10 +0900
commit648059575d16a21684897fab4be009e1fa757e4b (patch)
treef7321c9e0312692303d8612e6ad627594ffe3b10 /mrbgems/mruby-enum-ext/mrblib/enum.rb
parent86e69334ba7c4ba96960fcfe09c6cdec28e8c70c (diff)
parent767ca3f76ea510af3f6c430157c4e2f908c6651c (diff)
downloadmruby-648059575d16a21684897fab4be009e1fa757e4b.tar.gz
mruby-648059575d16a21684897fab4be009e1fa757e4b.zip
Merge pull request #1939 from suzukaze/add-enum.find_index
Enumerable#find_index
Diffstat (limited to 'mrbgems/mruby-enum-ext/mrblib/enum.rb')
-rw-r--r--mrbgems/mruby-enum-ext/mrblib/enum.rb36
1 files changed, 36 insertions, 0 deletions
diff --git a/mrbgems/mruby-enum-ext/mrblib/enum.rb b/mrbgems/mruby-enum-ext/mrblib/enum.rb
index bca69e08f..92c89a8f7 100644
--- a/mrbgems/mruby-enum-ext/mrblib/enum.rb
+++ b/mrbgems/mruby-enum-ext/mrblib/enum.rb
@@ -579,4 +579,40 @@ module Enumerable
end
end
end
+
+ ##
+ # call-seq:
+ # enum.find_index(value) -> int or nil
+ # enum.find_index { |obj| block } -> int or nil
+ # enum.find_index -> an_enumerator
+ #
+ # Compares each entry in <i>enum</i> with <em>value</em> or passes
+ # to <em>block</em>. Returns the index for the first for which the
+ # evaluated value is non-false. If no object matches, returns
+ # <code>nil</code>
+ #
+ # If neither block nor argument is given, an enumerator is returned instead.
+ #
+ # (1..10).find_index { |i| i % 5 == 0 and i % 7 == 0 } #=> nil
+ # (1..100).find_index { |i| i % 5 == 0 and i % 7 == 0 } #=> 34
+ # (1..100).find_index(50) #=> 49
+ #
+
+ def find_index(val=NONE, &block)
+ return to_enum :find_index if !block_given? && val == NONE
+
+ idx = 0
+ if block
+ self.each do |e|
+ return idx if block.call(e)
+ idx += 1
+ end
+ else
+ self.each do |e|
+ return idx if e == val
+ idx += 1
+ end
+ end
+ nil
+ end
end