lib/linked/list.rb in linked-0.5.1 vs lib/linked/list.rb in linked-0.5.2

- old
+ new

@@ -87,17 +87,11 @@ # @return [Listable, nil] the last item in the list, or nil if the list is # empty. def pop return nil if empty? - if list_tail.first? - item = last - @_chain = nil - item - else - list_tail.delete - end + list_tail.first? ? last.tap { @_chain = nil } : list_tail.delete end # Insert an item at the beginning of the list. If the given object is not an # object responding to #item it will be treated as a value. The value will # be wraped in a new Item create by #create_item. @@ -119,13 +113,11 @@ # empty. def shift return nil if empty? if list_head.last? - item = @_chain - @_chain = nil - item + @_chain.tap { @_chain = nil } else old_head = list_head @_chain = list_head.next old_head.delete end @@ -171,49 +163,49 @@ res.join("\n") end alias inspect inspect_list + protected + # Protected factory method for creating items compatible with the list. This # method is called whenever an arbitrary object is pushed or unshifted onto # the list and need to be wraped inside an Item. # # This method can be overridden to support different Item types. # # @param args [Array<Object>] the arguments that are to be passed on to # `Item.new`. # @return [Item] a new `Listable` item. - protected def create_item(*args) + def create_item(*args) Item.new(*args) end + private + # Takes an arbitrary object and coerces it into an item compliant with the # list. If the object is already an item it will be used as is. Otherwise # #create_item will be called with the object as an argument. # - # @param [#item, Object] the object to coerce. + # @param object [#item, Object] the object to coerce. # @return [Listable] see `#create_item`. - private def coerce_item(object) - if object.respond_to? :item - object.item - else - create_item object - end + def coerce_item(object) + object.respond_to?(:item) ? object.item : create_item(object) end # Private method for clearing the list and bringing it to a pristine # state. - private def reset_list + def reset_list @_chain = nil end # Returns the first item item in the list, or nil if empty. - private def list_head + def list_head @_chain end # Returns an the last item in the list, or nil if empty. - private def list_tail + def list_tail @_chain.last_in_chain end end end