Navigation Menu

Skip to content

Commit

Permalink
proper [] impl for List
Browse files Browse the repository at this point in the history
  • Loading branch information
jmettraux committed Jan 28, 2009
1 parent d08e640 commit a7fa300
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 8 deletions.
43 changes: 37 additions & 6 deletions lib/rufus/tokyo/util.rb
Expand Up @@ -255,10 +255,26 @@ def size

alias :length :size

def [] (i, count=-1)
# TODO : handle [1, 3] and [1..2]
i = i % self.size
lib.tclistval2(@list, i)
#
# The equivalent of Ruby Array#[]
#
def [] (i, count=nil)

return nil if (count != nil) && count < 1

len = self.size

range = if count.nil?
i.is_a?(Range) ? i : [i]
else
(i..i + count - 1)
end

#p [ range, norm(range) ]

r = norm(range).collect { |i| lib.tclistval2(@list, i) rescue nil }

range.first == range.last ? r.first : r
end

def clear
Expand All @@ -270,14 +286,14 @@ def each
end

#
# turns this Tokyo Cabinet list into a Ruby array
# Turns this Tokyo Cabinet list into a Ruby array
#
def to_a
self.collect { |e| e }
end

#
# closes (frees) this list
# Closes (frees) this list
#
def close
lib.tclistdel(@list)
Expand All @@ -286,6 +302,21 @@ def close

alias :free :close
alias :destroy :close

protected

#
# Makes sure this offset/range fits the size of the list
#
def norm (i)
l = self.length
case i
when Range then ((i.first % l)..(i.last % l))
when Array then [ i.first % l ]
else i % l
end
end

end
end

6 changes: 4 additions & 2 deletions test/util_list_test.rb
Expand Up @@ -26,8 +26,10 @@ def test_list_0
assert_equal 3, l.size
assert_equal 'bravo', l[1]
assert_equal 'charly', l[-1]
#assert_equal %w{ alpha bravo }, l[0, 2]
#assert_equal %w{ alpha bravo }, l[0..1]
assert_equal %w{ alpha bravo }, l[0, 2]
assert_equal %w{ alpha bravo charly }, l[0..-1]
assert_equal %w{ alpha bravo }, l[0..1]
assert_nil l[0, -1]

assert_equal %w{ ALPHA BRAVO CHARLY }, l.collect { |e| e.upcase }

Expand Down

0 comments on commit a7fa300

Please sign in to comment.