diff --git a/lib/git_stats/core_extensions/hash.rb b/lib/git_stats/core_extensions/hash.rb index 995fb370a..4fd5a947a 100644 --- a/lib/git_stats/core_extensions/hash.rb +++ b/lib/git_stats/core_extensions/hash.rb @@ -1,5 +1,6 @@ class Hash def to_key_indexed_array - self.inject([]) { |acc, (k, v)| acc[k] = v; acc } + raise ArgumentError.new('all the keys must be numbers to convert to key indexed array') unless all? { |k, v| k.is_a? Numeric } + inject([]) { |acc, (k, v)| acc[k] = v; acc } end end \ No newline at end of file diff --git a/spec/hash_extension_spec.rb b/spec/hash_extension_spec.rb new file mode 100644 index 000000000..4afd44e17 --- /dev/null +++ b/spec/hash_extension_spec.rb @@ -0,0 +1,15 @@ +require 'spec_helper' + +describe Hash do + context 'to_key_indexed_array' do + it 'should convert hash to array using keys as indexes' do + hash = {1 => 'x', 2 => 1, 5 => 'a'} + hash.to_key_indexed_array.should == [nil, 'x', 1, nil, nil, 'a'] + end + + it 'should throw exception if not all of the keys are numbers' do + hash = {1 => 'x', 'b' => 2} + expect { hash.to_key_indexed_array }.to raise_error(ArgumentError) + end + end +end \ No newline at end of file