hash#to_key_indexed_array spec

This commit is contained in:
Tomasz Gieniusz 2012-10-16 19:34:27 +02:00
parent c5c80cb382
commit 3a29083414
2 changed files with 17 additions and 1 deletions

View file

@ -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

View file

@ -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