From 174bb009effbb326a40741f8927e6e48692a6133 Mon Sep 17 00:00:00 2001 From: Sijawusz Pur Rahnama Date: Fri, 16 Dec 2022 00:21:50 +0100 Subject: [PATCH] Add `Indexable#rindex!` method variant (#12759) --- spec/std/indexable_spec.cr | 22 ++++++++++++++++++++++ src/indexable.cr | 14 ++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/spec/std/indexable_spec.cr b/spec/std/indexable_spec.cr index e2071cef0885..f7c39f7ba485 100644 --- a/spec/std/indexable_spec.cr +++ b/spec/std/indexable_spec.cr @@ -133,6 +133,28 @@ describe Indexable do end end + describe "#rindex!" do + it "does rindex with big negative offset" do + indexable = SafeIndexable.new(3) + expect_raises Enumerable::NotFoundError do + indexable.rindex!(0, -100) + end + end + + it "does rindex with big offset" do + indexable = SafeIndexable.new(3) + expect_raises Enumerable::NotFoundError do + indexable.rindex!(0, 100) + end + end + + it "offset type" do + indexable = SafeIndexable.new(3) + indexable.rindex!(1, 2_i64).should eq 1 + indexable.rindex!(1, 2_i64).should be_a(Int64) + end + end + it "does each" do indexable = SafeIndexable.new(3) is = [] of Int32 diff --git a/src/indexable.cr b/src/indexable.cr index 8ff5ddec14f4..8ce454a341ed 100644 --- a/src/indexable.cr +++ b/src/indexable.cr @@ -849,6 +849,13 @@ module Indexable(T) rindex(offset) { |elem| elem == value } end + # :ditto: + # + # Raises `Enumerable::NotFoundError` if *value* is not in `self`. + def rindex!(value, offset = size - 1) + rindex(value, offset) || raise Enumerable::NotFoundError.new + end + # Returns the index of the first object in `self` for which the block # is truthy, starting from the last object, or `nil` if no match # is found. @@ -872,6 +879,13 @@ module Indexable(T) nil end + # :ditto: + # + # Raises `Enumerable::NotFoundError` if no match is found. + def rindex!(offset = size - 1, & : T ->) + rindex(offset) { |e| yield e } || raise Enumerable::NotFoundError.new + end + # Optimized version of `Enumerable#sample` that runs in O(1) time. # # ```