Skip to content

Commit d4d6186

Browse files
committed
Add last to lists
For simplicity, this does not strictly respect Array#last when nil or false is passed, returning the last element instead of raising a TypeError.
1 parent 3b59b18 commit d4d6186

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

lib/kredis/types/list.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,19 @@ def append(*elements)
2424
def clear
2525
del
2626
end
27+
28+
def last(n = nil)
29+
if n
30+
n = n.to_int
31+
if n == 0
32+
[]
33+
elsif n < 0
34+
raise ArgumentError, "negative array size"
35+
else
36+
lrange(-n, -1)
37+
end
38+
else
39+
lrange(-1, -1).first
40+
end
41+
end
2742
end

test/types/list_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,19 @@ class ListTest < ActiveSupport::TestCase
4141
assert_equal [], @list.elements
4242
end
4343

44+
test "last" do
45+
@list.append(%w[ 1 2 3 ])
46+
assert_equal "3", @list.last
47+
end
48+
49+
test "last(n)" do
50+
@list.append(%w[ 1 2 3 ])
51+
assert_equal %w[ 2 3 ], @list.last(2)
52+
assert_equal %w[ 2 3 ], @list.last(2.0)
53+
assert_equal [], @list.last(0)
54+
assert_raises(ArgumentError) { @list.last(-2) }
55+
end
56+
4457
test "typed as datetime" do
4558
@list = Kredis.list "mylist", typed: :datetime
4659

0 commit comments

Comments
 (0)