Skip to content

Instantly share code, notes, and snippets.

@radar
Created February 16, 2009 22:27
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 radar/65417 to your computer and use it in GitHub Desktop.
Save radar/65417 to your computer and use it in GitHub Desktop.
# Original from Mitchell
def self.first_uninteresting
all_numbers = Number.find(:all).map { |entry| entry.number }.sort
last = 0
all_numbers.each do |number|
if number != last + 1
return last + 1
end
last = number
end
return last + 1
end
#-----------------------------------------------------------------------------------------
#NEW
class Interesting < ActiveRecord::Base
def self.lowest_number
previous = -1
all(:order=>:number, :conditions=>"number >= 0").each do |number|
break if previous != number.number - 1
previous = number.number
end
previous + 1
end
end
#==================
#Tests
require 'test_helper'
class InterestingTest < ActiveSupport::TestCase
def setup
Interesting.destroy_all
end
def test_should_return_lowest_number
[0, 1, 2, 3, 4, 6, 100].each {|value| Interesting.create(:number=>value)}
assert_equal 5, Interesting.lowest_number
end
def test_should_return_lowest_number_when_starts_at_1
[1,2,4].each {|value| Interesting.create(:number=>value)}
assert_equal 0, Interesting.lowest_number
end
def test_should_return_lowest_number_when_only_0_entry
[0].each {|value| Interesting.create(:number=>value)}
assert_equal 1, Interesting.lowest_number
end
def test_should_return_lowest_number_when_db_empty
assert_equal 0, Interesting.lowest_number
end
def test_should_return_lowest_number_and_ignore_negatives
[-10, -5, -3].each {|value| Interesting.create(:number=>value)}
assert_equal 0, Interesting.lowest_number
end
def test_should_return_lowest_number_and_ignore_negatives_and_still_return_next_positive_number
[-10, -5, -3, 0, 1, 2, 10].each {|value| Interesting.create(:number=>value)}
assert_equal 3, Interesting.lowest_number
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment