Skip to content

Instantly share code, notes, and snippets.

@ashleygwilliams
Created November 15, 2013 14:02
Show Gist options
  • Save ashleygwilliams/7484736 to your computer and use it in GitHub Desktop.
Save ashleygwilliams/7484736 to your computer and use it in GitHub Desktop.
# Write a method `format` for the class integer that converts the number to a
# string and adds commas at the appropriate places
#To test your solution run `rspec format_number_spec.rb` in your terminal
class Integer
def format
#code goes here...
end
end
class Integer
def format
to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
end
end
require './format_number'
describe Integer, "#format" do
it "should return a string with a comma every 3 char starting from the right for 4 digit numbers" do
1000.format.should eq("1,000")
end
it "should return a string with a comma every 3 char starting from the right for 4+ digit numbers " do
1000000.format.should eq("1,000,000")
end
it "should return a string with no commas if the number is < 4 char" do
100.format.should eq("100")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment