Module: Linked::ListEnumerable
Overview
Expects the list to implement #list_head and #list_tail.
Instance Method Summary collapse
-
#count(*args) ⇒ Integer
Overrides the Enumerable#count method when given no argument to provide a fast item count.
-
#each_item ⇒ Object
(also: #each)
Iterates over each item in the list If a block is not given an enumerator is returned.
-
#first(n = nil) ⇒ Listable+
Access the first n item(s) in the list.
-
#last(n = nil) ⇒ Listable+
Access the first n item(s) in the list.
-
#reverse_each_item {|Listable| ... } ⇒ Enumerable
(also: #reverse_each)
Iterates over each item in the list in reverse order.
Instance Method Details
#count(*args) ⇒ Integer
Overrides the Enumerable#count method when given no argument to provide a fast item count. Instead of iterating over each item, the internal item count is returned.
75 76 77 78 79 80 81 |
# File 'lib/linked/list_enumerable.rb', line 75 def count(*args) if args.empty? && !block_given? empty? ? 0 : list_head.chain_length else super end end |
#each_item ⇒ Object Also known as: each
Iterates over each item in the list If a block is not given an enumerator is returned.
10 11 12 13 14 15 16 17 18 19 |
# File 'lib/linked/list_enumerable.rb', line 10 def each_item return to_enum(__method__) { count } unless block_given? return if empty? item = list_head loop do yield item item = item.next end end |
#first(n = nil) ⇒ Listable+
Access the first n item(s) in the list.
46 47 48 49 50 51 52 53 |
# File 'lib/linked/list_enumerable.rb', line 46 def first(n = nil) return list_head unless n raise ArgumentError, 'n cannot be negative' if n.negative? return [] if n.zero? || empty? list_head.take n end |
#last(n = nil) ⇒ Listable+
Access the first n item(s) in the list.
60 61 62 63 64 65 66 67 |
# File 'lib/linked/list_enumerable.rb', line 60 def last(n = nil) return empty? ? nil : list_tail unless n raise ArgumentError, 'n cannot be negative' if n.negative? return [] if n.zero? || empty? list_tail.take(-n) end |
#reverse_each_item {|Listable| ... } ⇒ Enumerable Also known as: reverse_each
Iterates over each item in the list in reverse order. If a block is not given an enumerator is returned.
28 29 30 31 32 33 34 35 36 37 |
# File 'lib/linked/list_enumerable.rb', line 28 def reverse_each_item return to_enum(__method__) { count } unless block_given? return if empty? item = list_tail loop do yield item item = item.prev end end |