Class: Eg::Book::Money

Inherits:
Object
  • Object
show all
Defined in:
lib/eg/book/calculate_discount_money.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(amount = 0) ⇒ Money

Returns a new instance of Money.



16
17
18
# File 'lib/eg/book/calculate_discount_money.rb', line 16

def initialize amount = 0
  @cents = (amount * 100 + 0.5).to_i
end

Instance Attribute Details

#centsObject (readonly)

Returns the value of attribute cents.



15
16
17
# File 'lib/eg/book/calculate_discount_money.rb', line 15

def cents
  @cents
end

Class Method Details

.parse(string) ⇒ Object

Raises:

  • (Exception)


28
29
30
31
32
33
34
# File 'lib/eg/book/calculate_discount_money.rb', line 28

def Money.parse string
  raise Exception.new('Invalid money value') unless string =~ /^\$/
  dot = string.index '.'
  raise Exception.new('Invalid money value') if dot.nil? or dot != string.size - 3
  money = string[1..-1].to_f
  Money.new money
end

Instance Method Details

#*(times) ⇒ Object



22
23
24
# File 'lib/eg/book/calculate_discount_money.rb', line 22

def * times
  Money.new(@cents / 100.0 * times)
end

#==(money) ⇒ Object



25
26
27
# File 'lib/eg/book/calculate_discount_money.rb', line 25

def == money
  money.class == Money and @cents == money.cents
end

#>=(money) ⇒ Object



19
20
21
# File 'lib/eg/book/calculate_discount_money.rb', line 19

def >= money
  @cents >= money.cents
end

#to_sObject



35
36
37
38
39
# File 'lib/eg/book/calculate_discount_money.rb', line 35

def to_s
  cent_string = "#{@cents % 100}"
  cent_string += '0' if cent_string.size == 1
  "$#{cents / 100}.#{cent_string}"
end