Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/money/core_extensions.rb
Instance Method Summary collapse
-
#to_money ⇒ Object
Parses the current string and converts it to a Money object.
Instance Method Details
#to_money ⇒ 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">
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/money/core_extensions.rb', line 21 def to_money # Get the currency. matches = scan /([A-Z]{2,3})/ currency = matches[0] ? matches[0][0] : Money.default_currency # Get the cents amount sans_spaces = gsub(/\s+/, '') matches = sans_spaces.scan /(\-?\d+(?:[\.,]\d+)?)/ cents = if matches[0] value = matches[0][0].gsub(/,/, '.') value.to_f * 100 else 0 end Money.new(cents, currency) end |