Created
October 2, 2013 16:45
-
-
Save langalex/6796684 to your computer and use it in GitHub Desktop.
A data structure to put stuff in and take it out again. NIH syndrome?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Bag | |
def initialize | |
@contents = Hash.new(0) | |
end | |
def put_in(names, amount) | |
@contents[[names].flatten] += amount | |
end | |
def take_out(name, amount) | |
bag_key = @contents.keys.find{|k| k.include?(name)} | |
available = [amount, @contents[bag_key]].min | |
@contents[bag_key] -= available | |
available | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe Bag do | |
let(:bag) { Bag.new } | |
it 'only lets me take out what i put in' do | |
bag.put_in :tshirt, 2 | |
expect(bag.take_out(:tshirt, 3)).to eql(2) | |
end | |
it 'returns 0 if there is nothing left' do | |
bag.put_in :tshirt, 2 | |
bag.take_out(:tshirt, 2) | |
expect(bag.take_out(:tshirt, 1)).to eql(0) | |
end | |
it 'lets me put in items under multiple names' do | |
bag.put_in [:tshirt, :polo], 2 | |
expect(bag.take_out(:tshirt, 1)).to eql(1) | |
expect(bag.take_out(:polo, 1)).to eql(1) | |
expect(bag.take_out(:tshirt, 1)).to eql(0) | |
expect(bag.take_out(:polo, 1)).to eql(0) | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment