User Tools

Site Tools


Differences

This shows you the differences between two versions of the page.

Link to this comparison view

ruby:object [2019-11-26 12:25] (current)
ziggi created
Line 1: Line 1:
 +<code ruby index.rb>​
 +#
 +#  Copyright 2019 Oleg Borodin ​ <​borodin@unix7.org>​
 +#
 +
 +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
 +</​code>​
 +
 +===Out===
 +
 +<​file>​
 +$ ruby index.rb ​
 +item: foo cost: 10
 +item: bar cost: 10
 +sum: 20
 +</​file>​