Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/money/core_extensions.rb

Instance Method Summary collapse

Instance Method Details

#to_money(with_cents = false) ⇒ Object

Parses the current string and converts it to a Money object. Excess characters will be discarded.

'100'.to_money       # => #<Money @cents=10000>
'100.37'.to_money    # => #<Money @cents=10037>
'100 USD'.to_money   # => #<Money @cents=10000, @currency="USD">
'USD 100'.to_money   # => #<Money @cents=10000, @currency="USD">
'$100 USD'.to_money  # => #<Money @cents=10000, @currency="USD">
'hello 2000 world'.to_money   # => #<Money @cents=200000 @currency="USD")>


31
32
33
34
35
36
37
# File 'lib/money/core_extensions.rb', line 31

def to_money(with_cents = false)
  # Get the currency.
  matches = scan /([A-Z]{2,3})/
  currency = matches[0] ? matches[0][0] : Money.default_currency
  cents = calculate_cents(self, with_cents)
  Money.new(cents, currency)
end