Created
April 7, 2014 20:14
-
-
Save davejlong/10043548 to your computer and use it in GitHub Desktop.
Changing my thought process with Ruby
This file contains hidden or 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
| # 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 |
This file contains hidden or 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
| # 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 |
This file contains hidden or 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
| # 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