From 767ca3f76ea510af3f6c430157c4e2f908c6651c Mon Sep 17 00:00:00 2001 From: Jun Hiroe Date: Tue, 25 Mar 2014 16:06:25 +0900 Subject: Enumerable#find_index --- mrbgems/mruby-enum-ext/mrblib/enum.rb | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'mrbgems/mruby-enum-ext/mrblib') 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 enum with value or passes + # to block. Returns the index for the first for which the + # evaluated value is non-false. If no object matches, returns + # nil + # + # 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 -- cgit v1.2.3