Created
October 1, 2012 03:07
-
-
Save havenwood/3809258 to your computer and use it in GitHub Desktop.
Ruby 2.0 Refined #only? Method on Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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