Class: Bag
Instance Method Summary collapse
-
#add(amount, item) ⇒ Object
> Insertions / Deletions.
- #add_all(other) ⇒ Object
-
#each(&block) ⇒ Object
> Iterating.
- #empty? ⇒ Boolean
-
#has?(amount, item) ⇒ Boolean
> Booleans Do we have the item?.
-
#initialize ⇒ Bag
constructor
Create the bag.
-
#print ⇒ Object
> Formating Let me know how many things are in my bag man.
-
#remove(amount, item) ⇒ Object
Someone bought my things.
- #remove_all(other) ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize ⇒ Bag
Create the bag
6 7 8 |
# File 'lib/inventory/bag.rb', line 6 def initialize @bag = Hash.new end |
Instance Method Details
#add(amount, item) ⇒ Object
> Insertions / Deletions
25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/inventory/bag.rb', line 25 def add(amount, item) unless amount > 0 raise Exceptions::NotEnoughError "Value must be greater than 0" end if @bag.has_key?(item) @bag[item] += amount else @bag[item] = amount end end |
#add_all(other) ⇒ Object
38 39 40 41 42 |
# File 'lib/inventory/bag.rb', line 38 def add_all(other) other.each do |item, amount| self.add(amount, item) end end |
#each(&block) ⇒ Object
> Iterating
68 69 70 |
# File 'lib/inventory/bag.rb', line 68 def each(&block) @bag.each(&block) end |
#empty? ⇒ Boolean
20 21 22 |
# File 'lib/inventory/bag.rb', line 20 def empty? @bag.size == 0 end |
#has?(amount, item) ⇒ Boolean
> Booleans
Do we have the item?
16 17 18 |
# File 'lib/inventory/bag.rb', line 16 def has?(amount, item) @bag.has_key?(item) and @bag[item] >= amount end |
#print ⇒ Object
> Formating
Let me know how many things are in my bag man.
74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/inventory/bag.rb', line 74 def print buffer = [] if @bag.empty? buffer << "Bag is empty" else buffer << "Current Inventory" @bag.each do |item, amount| buffer << " #{item}: #{amount}" end end buffer end |
#remove(amount, item) ⇒ Object
Someone bought my things
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/inventory/bag.rb', line 45 def remove(amount, item) if @bag.empty? puts "empty bag" return elsif !self.has?(amount, item) puts "not enough" else @bag[item] -= amount end end |
#remove_all(other) ⇒ Object
56 57 58 59 60 61 62 63 64 65 |
# File 'lib/inventory/bag.rb', line 56 def remove_all(other) if @bag.empty? puts "empty bag" return else other.each do |item, amount| self.remove(amount, item) end end end |
#size ⇒ Object
10 11 12 |
# File 'lib/inventory/bag.rb', line 10 def size @bag.size end |