Skip to content

Instantly share code, notes, and snippets.

@davejlong
Created April 7, 2014 20:14
Show Gist options
  • Select an option

  • Save davejlong/10043548 to your computer and use it in GitHub Desktop.

Select an option

Save davejlong/10043548 to your computer and use it in GitHub Desktop.
Changing my thought process with Ruby
# Code is way too verbose
class HashStore
attr_writer :store
def store
@store ||= Hash.new
end
def add_value(scope, value)
it store.has_key?(scope) && store[scope].is_a?(Array)
store[scope] << value
else
store[scope] = [value]
end
end
end
# Much cleaner. No forking and 30% reduction in LOC
class HashStore
attr_writer :store
def store
@store ||= Hash.new(Array.new)
end
def add_value(scope, value)
store[scope] << value
end
end
# To run the spec download all three files and run either of the 2 commands:
#
# $ rspec -r ./bad_hash_store.rb hash_store_spec.rb
# $ rspec -r ./good_hash_store.rb hash_store_spec.rb
describe HashStore do
let(:store) { HashStore.new }
before(:each) { store.ad_value :hello, :world }
it 'adds a new key to the store' do
expect(store.store[:hello]).to include :world
end
it 'appends a value to an existing key' do
store.add_value :hello, :foo_bar
expect(store.store[:hello]).to include :foo_bar
expect(store.store[:hello]).to include :world
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment