Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions internal/vm/array_edges_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,25 @@ func TestArrayCycle(t *testing.T) {
}
}
}

// TestArrayRindex covers Array#rindex — value form, block form (with the
// argument winning over a block), the no-argument sized Enumerator and the
// no-match nil. Asserted against MRI Ruby 4.0.6.
func TestArrayRindex(t *testing.T) {
cases := []struct{ src, want string }{
{`p [1, 2, 3, 2, 1].rindex(2)`, "3\n"},
{`p [1, 2, 3].rindex(9)`, "nil\n"},
{`p [].rindex(1)`, "nil\n"},
{`p [1, 2, 3, 2, 1].rindex { |x| x == 2 }`, "3\n"},
{`p [1, 2, 3].rindex { |x| x > 5 }`, "nil\n"},
{`p [1, 2, 3].rindex.class`, "Enumerator\n"},
{`p [1, 2, 3, 2].rindex.to_a`, "[2, 3, 2, 1]\n"},
{`e = [1, 2, 3, 2].rindex; p e.each { |x| x == 2 }`, "3\n"},
{`p [1, 2, 3, 2, 1].rindex(2) { |x| x == 3 }`, "3\n"}, // argument wins over block
}
for _, c := range cases {
if got := eval(t, c.src); got != c.want {
t.Errorf("src=%q got=%q want=%q", c.src, got, c.want)
}
}
}
22 changes: 22 additions & 0 deletions internal/vm/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -3270,6 +3270,28 @@ func (vm *VM) bootstrap() {
}
return object.NilV
})
// rindex searches backward from the end: rindex(obj) → the last index whose
// element == obj; rindex { |e| … } → the last index whose block is truthy (an
// argument, if given, wins over the block); no argument and no block → a sized
// Enumerator. Returns nil when nothing matches.
vm.cArray.define("rindex", func(vm *VM, self object.Value, args []object.Value, blk *Proc) object.Value {
a := self.(*object.Array)
if len(args) == 0 && blk == nil {
return enumForSized(self, "rindex", func(*VM) object.Value { return object.IntValue(int64(len(a.Elems))) })
}
for i := len(a.Elems) - 1; i >= 0; i-- {
var match bool
if len(args) > 0 {
match = valueEqual(a.Elems[i], args[0])
} else {
match = vm.callBlock(blk, []object.Value{a.Elems[i]}).Truthy()
}
if match {
return object.IntValue(int64(i))
}
}
return object.NilV
})
vm.cArray.define("assoc", func(vm *VM, self object.Value, args []object.Value, _ *Proc) object.Value {
return vm.arrayAssoc(self.(*object.Array), args[0], 0)
})
Expand Down
2 changes: 1 addition & 1 deletion scripts/conformance/rubyspec/FLOOR
Original file line number Diff line number Diff line change
@@ -1 +1 @@
15820
15830