Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created October 1, 2012 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/3809258 to your computer and use it in GitHub Desktop.
Save havenwood/3809258 to your computer and use it in GitHub Desktop.
Ruby 2.0 Refined #only? Method on Array
module Only
refine Array do
def only?
case self.size
when 1
self.first
when 0
nil
else
false
end
end
end
end
require 'minitest/autorun'
require 'minitest/pride'
describe Array do
using Only
describe 'a single element' do
it 'returns the element' do
assert_equal 0, [0].only?
assert_equal 'Just me!', ['Just me!'].only?
end
end
describe 'multiple elements' do
it 'returns false' do
assert_equal false, [1.0/0, 2.71828].only?
assert_equal false, %w[O M G W T F B B Q].only?
end
end
describe 'no elements' do
it 'returns nil' do
assert_nil [].only?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment