Skip to content

Commit 02c42fa

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. It also doesn't coerce the parameter into an int with to_int like Array#last does.
1 parent 3b59b18 commit 02c42fa

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

lib/kredis/types/list.rb

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

test/types/list_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,18 @@ 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 [], @list.last(0)
53+
assert_raises(ArgumentError) { @list.last(-2) }
54+
end
55+
4456
test "typed as datetime" do
4557
@list = Kredis.list "mylist", typed: :datetime
4658

0 commit comments

Comments
 (0)