User Tools

Site Tools


index.rb
#
#  Author, Copyright: Oleg Borodin <onborodin@gmail.com>
#
 
class Index
 
    def initialize
        @items = Hash.new
        @sum = 0
    end
 
    def add(name, cost)
        if !@items[name]
            @items[name] = cost
            @sum += cost
        end
    end
 
    def delete(name)
        cost = @items[name]
        if cost
            @sum -= cost
            @items.delete(name)
        end
    end
 
    def print
        @items.each do |key, value|
            puts "item: #{key} cost: #{value}"
        end
        puts "sum: #{@sum}"
    end
 
end
 
i = Index.new
i.add("foo", 10)
i.add("bar", 10)
i.add("some", 10)
i.delete("some")
i.print

Out

$ ruby index.rb 
item: foo cost: 10
item: bar cost: 10
sum: 20