Class: History

Inherits:
Object
  • Object
show all
Defined in:
lib/history.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(length, show_num_items = 5) ⇒ History

Returns a new instance of History.



5
6
7
8
9
# File 'lib/history.rb', line 5

def initialize length, show_num_items = 5
    @items = {}
    self.length = length
    self.show_num_items = show_num_items
end

Instance Attribute Details

#lengthObject

Returns the value of attribute length.



3
4
5
# File 'lib/history.rb', line 3

def length
  @length
end

#show_num_itemsObject

Returns the value of attribute show_num_items.



3
4
5
# File 'lib/history.rb', line 3

def show_num_items
  @show_num_items
end

Instance Method Details

#clearObject



24
25
26
# File 'lib/history.rb', line 24

def clear
    @items = {}
end

#itemsObject



19
20
21
22
# File 'lib/history.rb', line 19

def items 
    sorted_items = (@items.sort_by {|item,age| age}).map {|pair| pair.first}
    sorted_items.partition {|item| sorted_items.index(item) < (@show_num_items)}
end

#update(item) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/history.rb', line 11

def update item
    @items.each {|itm,age| @items[itm] += 1}
    @items[item] = 0
    if @items.length > @length
        @items.delete((@items.max_by {|itm, age| age}).first)
    end
end