Created
March 15, 2013 21:08
-
-
Save gmanley/5173116 to your computer and use it in GitHub Desktop.
Just to illustrate how you would go about reimplementing group_by.
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
require 'rspec' | |
class Array | |
def custom_group_by(&block) | |
results = {} | |
each do |e| | |
(results[block.call(e)] ||= []) << e | |
end | |
results | |
end | |
end | |
describe Array do | |
let(:array) { ['a', 2, :blah, 3, 'b'] } | |
describe '#custom_group_by' do | |
it 'groups elements in a hash by the result of the given block' do | |
grouped_hash = array.custom_group_by { |e| e.class.name.downcase.to_sym } | |
expect(grouped_hash).to eql({ | |
symbol: [:blah], | |
string: ['a', 'b'], | |
fixnum: [2, 3] | |
}) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment