diff --git a/lib/array.rb b/lib/array.rb index 5a12e4d..f82e2b7 100644 --- a/lib/array.rb +++ b/lib/array.rb @@ -16,4 +16,8 @@ def as_hash(keys) def random self[rand(size)] end + + def random! + self.slice!(rand(size)) + end end diff --git a/lib/bidu/core_ext/version.rb b/lib/bidu/core_ext/version.rb index 97c44f7..5c13a21 100644 --- a/lib/bidu/core_ext/version.rb +++ b/lib/bidu/core_ext/version.rb @@ -1,5 +1,5 @@ module Bidu module CoreExt - VERSION = '1.2.1' + VERSION = '1.2.2' end end diff --git a/spec/lib/array_spec.rb b/spec/lib/array_spec.rb index 9f190ee..33e977d 100644 --- a/spec/lib/array_spec.rb +++ b/spec/lib/array_spec.rb @@ -92,18 +92,18 @@ end describe '#random' do - let(:array) { [ 7, 5, 3 ] } + it_behaves_like 'a method that returns a random element', :random + end - (0..2).each do |index| - context "when random returns #{index}" do - before do - allow_any_instance_of(Array).to receive(:rand).with(array.size) { index } - end + describe '#random!' do + it_behaves_like 'a method that returns a random element', :random! - it 'returns the randomized index of the array' do - expect(array.random).to eq(array[index]) - end - end + let(:array) { [ 8,4,2 ] } + + it 'removes an the returned element' do + expect do + array.random! + end.to change { array.size }.by(-1) end end diff --git a/spec/support/shared_examples/array_random.rb b/spec/support/shared_examples/array_random.rb new file mode 100644 index 0000000..869c578 --- /dev/null +++ b/spec/support/shared_examples/array_random.rb @@ -0,0 +1,16 @@ +shared_examples 'a method that returns a random element' do |method| + let(:array) { [ 7, 5, 3 ] } + + (0..2).each do |index| + context "when random returns #{index}" do + let!(:expected) { array[index] } + before do + allow_any_instance_of(Array).to receive(:rand).with(array.size) { index } + end + + it 'returns the randomized index of the array' do + expect(array.public_send(method)).to eq(expected) + end + end + end +end