Skip to content

Instantly share code, notes, and snippets.

@langalex
Created October 2, 2013 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save langalex/6796684 to your computer and use it in GitHub Desktop.
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?
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
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