Skip to content

Instantly share code, notes, and snippets.

@tiegz
Created June 9, 2012 05:58
Show Gist options
  • Save tiegz/2899696 to your computer and use it in GitHub Desktop.
Save tiegz/2899696 to your computer and use it in GitHub Desktop.
Using the method Array#one? in ruby
# The method Array#one? in ruby is intended to be used with a block. It does *not* signify that
# there is one element in the array:
1.8.7 :066 > [1,2,3].one?
=> false
1.8.7 :067 > [1,nil,nil].one?
=> true
# Also, it is slower than just checking the array's size:
1.8.7 :047 > Benchmark.ms { 10000.times { [1,2,3].size == 1 } }
=> 7.34710693359375
1.8.7 :055 > Benchmark.ms { 10000.times { [1,2,3].one? } }
=> 13.7670040130615
# The method Array#one? in ruby is intended to be used with a block. It does *not* signify that
# there is one element in the array:
1.8.7 :066 > [1,2,3].one?
=> false
1.8.7 :067 > [1,nil,nil].one?
=> true
# Also, it is slower than just checking the array's size:
1.8.7 :047 > Benchmark.ms { 10000.times { [1,2,3].size == 1 } }
=> 7.34710693359375
1.8.7 :055 > Benchmark.ms { 10000.times { [1,2,3].one? } }
=> 13.7670040130615
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment