Skip to content

Commit 301d83e

Browse files
committed
Make List#last more similar to Array#last
At the expense of some complexity, this handles properly nil or false being passed as an argument by using a specific value to encode that no arguments were passed to the method. It still raises a NoMethodError to_int instead of a TypeError, but the additional complexity is not worth the runtime cost IMO.
1 parent d4d6186 commit 301d83e

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

lib/kredis/types/list.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,11 @@ def clear
2525
del
2626
end
2727

28-
def last(n = nil)
29-
if n
28+
NO_ARGUMENT = Object.new
29+
private_constant :NO_ARGUMENT
30+
31+
def last(n = NO_ARGUMENT)
32+
if n != NO_ARGUMENT
3033
n = n.to_int
3134
if n == 0
3235
[]

test/types/list_test.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ class ListTest < ActiveSupport::TestCase
5252
assert_equal %w[ 2 3 ], @list.last(2.0)
5353
assert_equal [], @list.last(0)
5454
assert_raises(ArgumentError) { @list.last(-2) }
55+
assert_raises { @list.last(nil) }
56+
assert_raises { @list.last(false) }
57+
assert_raises { @list.last(BasicObject.new) }
5558
end
5659

5760
test "typed as datetime" do

0 commit comments

Comments
 (0)