Skip to content

Instantly share code, notes, and snippets.

@sferik
Created January 27, 2012 01:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sferik/1686355 to your computer and use it in GitHub Desktop.
Save sferik/1686355 to your computer and use it in GitHub Desktop.
# Helper function that returns a number with its correct indefinite article
# e.g. number_with_indefinite_article(10) #=> "a 10"
# e.g. number_with_indefinite_article(80, "$") #=> "an $80"
def number_with_indefinite_article(number, prefix=nil)
[indefinite_article_for_number(number), " ", prefix, number].compact.join
end
# Helper function that returns the correct indefinite article for a number
# e.g. indefinite_article_for_number(10) #=> "a"
# e.g. indefinite_article_for_number(80) #=> "an"
def indefinite_article_for_number(number)
number_s = number.to_s
# There are only 3 kinds of numbers that take the article "an" instead of "a":
# 1. Any number that starts with an 8
# 2. Numbers like 11, 11,000 or 11,000,000 (but not 110,000 or 1,100,000)
# 3. Numbers like 18, 18,000 or 18,000,000 (but not 180,000 or 1,800,000)
(number_s[0, 1] == "8" || (number_s.size % 3 == 2 && (number_s[0, 2] == "11" || number_s[0, 2] == "18"))) ? "an" : "a"
end
require 'rspec'
describe "#number_with_indefinite_article" do
context "without a prefix" do
it "returns a number with its correct indefinite article" do
number_with_indefinite_article(1).should == "a 1"
number_with_indefinite_article(8).should == "an 8"
end
end
context "with a prefix" do
it "returns a number with its correct indefinite article and prefix" do
number_with_indefinite_article(1, "$").should == "a $1"
number_with_indefinite_article(8, "$").should == "an $8"
end
end
end
describe "#indefinite_article_for_number" do
it "returns the correct indefinite article for a number" do
[1, 7, 9, 10, 12, 100, 110_000, 180_000, 1_100_000, 1_800_000].each do |number|
indefinite_article_for_number(number).should == "a"
end
[8, 11, 18, 11_000, 18_000, 11_000_000, 18_000_000].each do |number|
indefinite_article_for_number(number).should == "an"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment