class Rledger::Amount

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)

Public Class Methods

new() click to toggle source
# File lib/rledger/ledger/amount.rb, line 10
def initialize
  @amount = Hash.new
end

Public Instance Methods

add!(other_amount) click to toggle source
# 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
amount() click to toggle source

good only if single amount

# File lib/rledger/ledger/amount.rb, line 58
def amount
  @amount[@amount.keys[0]]
end
amount_of(currency) click to toggle source
# File lib/rledger/ledger/amount.rb, line 53
def amount_of currency
  @amount[currency]
end
currencies() click to toggle source
# File lib/rledger/ledger/amount.rb, line 49
def currencies 
  @amount.keys
end
currency() click to toggle source

good only if single currency

# File lib/rledger/ledger/amount.rb, line 63
def currency
  @amount.keys[0]
end
hash() click to toggle source
# File lib/rledger/ledger/amount.rb, line 67
def hash
  @amount
end
multiply!(factor) click to toggle source
# File lib/rledger/ledger/amount.rb, line 40
def multiply!(factor)
  @amount.keys.map { |x| @amount[x] = factor * @amount[x] }
  self
end
parse(s) click to toggle source
# 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?() click to toggle source
# File lib/rledger/ledger/amount.rb, line 45
def single_currency?
  @amount.keys.size == 1
end
to_s() click to toggle source
# File lib/rledger/ledger/amount.rb, line 31
def to_s
  @amount.keys.collect { |key| key + " " + "%.2f" % @amount[key] }.join(", ")
end