Skip to content

Commit

Permalink
Add Indexable#rindex! method variant (#12759)
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija authored Dec 15, 2022
1 parent f0003ed commit 174bb00
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
22 changes: 22 additions & 0 deletions spec/std/indexable_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions src/indexable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
#
# ```
Expand Down

0 comments on commit 174bb00

Please sign in to comment.