Skip to content

Commit

Permalink
Merge pull request #14 from Bidu/ff-random
Browse files Browse the repository at this point in the history
Add Array#random!
  • Loading branch information
darthjee committed Jun 16, 2016
2 parents 52e0c42 + 78cc7d5 commit 083db91
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 11 deletions.
4 changes: 4 additions & 0 deletions lib/array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@ def as_hash(keys)
def random
self[rand(size)]
end

def random!
self.slice!(rand(size))
end
end
2 changes: 1 addition & 1 deletion lib/bidu/core_ext/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module Bidu
module CoreExt
VERSION = '1.2.1'
VERSION = '1.2.2'
end
end
20 changes: 10 additions & 10 deletions spec/lib/array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 16 additions & 0 deletions spec/support/shared_examples/array_random.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 083db91

Please sign in to comment.