Created
November 12, 2010 15:35
-
-
Save cmhobbs/674227 to your computer and use it in GitHub Desktop.
duck punchin' #to_cents method and some tests
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
class String | |
def to_cents | |
regex = /[\,$]/ | |
if self.match(regex) | |
self.gsub!(regex, "") | |
end | |
if self.match(/\./) | |
dollars, change = self.split(".") | |
(dollars + change).to_i | |
else | |
self.to_i * 100 | |
end | |
end | |
end | |
class Float | |
def to_cents | |
self.to_i * 100 | |
end | |
end | |
class Fixnum | |
def to_cents | |
self * 100 | |
end | |
end |
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
require './cents.rb' | |
describe String do | |
describe "to_cents" do | |
it "should convert currency in strings with commas into cents properly" do | |
"1,000".to_cents.should == 100000 | |
end | |
it "should convert currency strings with commas and decimals properly" do | |
"1,000.00".to_cents.should == 100000 | |
end | |
it "should convert currency strings properly" do | |
"1000".to_cents.should == 100000 | |
end | |
it "should convert currency strings with change properly" do | |
"1000.23".to_cents.should == 100023 | |
end | |
it "should convert currency strings with commas and change properly" do | |
"1,100.23".to_cents.should == 110023 | |
end | |
it "should convert currency strings with commas decimals and dolla signs properly" do | |
"$1,100.23".to_cents.should == 110023 | |
end | |
end | |
end | |
describe Float do | |
describe "to_cents" do | |
it "should convert whole values with change properly" do | |
1000.00.to_cents.should == 100000 | |
end | |
end | |
end | |
describe Fixnum do | |
describe "to_cents" do | |
it "should convert whole values without change properly" do | |
1000.to_cents.should == 100000 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment