Class: Rledger::Amount

Inherits:
Object
  • Object
show all
Defined in:
lib/rledger/ledger/amount.rb

Overview

Amount stores an amount, as an Hash currency => value.

The peculiar storage simplifies operations on multiple currencies (adding different currencies is equivalent to merging hashes)

Instance Method Summary collapse

Constructor Details

#initializeAmount

Returns a new instance of Amount.



10
11
12
# File 'lib/rledger/ledger/amount.rb', line 10

def initialize
  @amount = Hash.new
end

Instance Method Details

#add!(other_amount) ⇒ Object



35
36
37
38
# File 'lib/rledger/ledger/amount.rb', line 35

def add!(other_amount)
  @amount.merge!(other_amount.hash) { |key, oldval, newval| @amount[key] = oldval + newval } 
  self
end

#amountObject

good only if single amount



58
59
60
# File 'lib/rledger/ledger/amount.rb', line 58

def amount
  @amount[@amount.keys[0]]
end

#amount_of(currency) ⇒ Object



53
54
55
# File 'lib/rledger/ledger/amount.rb', line 53

def amount_of currency
  @amount[currency]
end

#currenciesObject



49
50
51
# File 'lib/rledger/ledger/amount.rb', line 49

def currencies 
  @amount.keys
end

#currencyObject

good only if single currency



63
64
65
# File 'lib/rledger/ledger/amount.rb', line 63

def currency
  @amount.keys[0]
end

#hashObject



67
68
69
# File 'lib/rledger/ledger/amount.rb', line 67

def hash
  @amount
end

#multiply!(factor) ⇒ Object



40
41
42
43
# File 'lib/rledger/ledger/amount.rb', line 40

def multiply!(factor)
  @amount.keys.map { |x| @amount[x] = factor * @amount[x] }
  self
end

#parse(s) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/rledger/ledger/amount.rb', line 14

def parse(s)
  currency = "([a-zA-Z$]+|)"
  amount = "(-?[0-9]+\\.?[0-9]+|)"
  ob = "[\t ]*"
  
  match = Regexp.new(currency + ob + amount).match(s)

  if match
    currency = match[1]
    amount   = match[2] == "" ?  BigDecimal.new('0.00') : BigDecimal.new(match[2])
    @amount[currency] = amount
    true
  else
    false
  end
end

#single_currency?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/rledger/ledger/amount.rb', line 45

def single_currency?
  @amount.keys.size == 1
end

#to_sObject



31
32
33
# File 'lib/rledger/ledger/amount.rb', line 31

def to_s
  @amount.keys.collect { |key| key + " " + "%.2f" % @amount[key] }.join(", ")
end