2

I have a String and i need to convert it into Currency format in RUBY and verify whether it matches to the expected.

String = "$6,178.50 USD / 22,693.01 AED"

I want to split it into 2 different variables like

usa_price = $6,178.50

aed_price = 22,693.01

expected_output= $6,178.50 * 3.67 = 22,693.01 (should match value in AED)

I tried doing gsub/scan and im confused now, what's the best way to achieve this in Ruby!!!

QualityThoughts
  • 79
  • 1
  • 2
  • 9

2 Answers2

7

I would split on the / and then use the money gem to parse the amounts out, like this:

require 'money'
amounts = "$6,178.50 USD / 22,693.01 AED".split("/")
amounts.map! { |amount| Money.parse(amount) }

Then, because they're now Money objects, you can do money things with them:

>> amounts.first.format
=> "$6,178.50"
Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
1

If you're sure that first number is USD and second number is AED and the order won't change then:

str = "$6,178.50 USD / 22,693.01 AED"

usa_price, aed_price = str.scan(/\d{1,2}?,?\d{1,3}\.\d{2}/)

#=> usa_price = 6,178.50, aed_price = 22,693.01
megas
  • 21,401
  • 12
  • 79
  • 130
  • 1
    Will this solution work for non-thousand dollar amounts, i.e. $178.50? – Ryan Bigg Oct 10 '12 at 00:10
  • How about amounts in the hundreds of thousands? – Ryan Bigg Oct 10 '12 at 00:57
  • Or in the millions, or billions, or trillions, or quadrillions, or quintillions, or sextillions, or septillions, or octillions... basically, any unit listed here: https://github.com/radar/humanize/blob/master/lib/lots.rb – Ryan Bigg Oct 10 '12 at 01:05
  • The point I'm trying to (perhaps excessively) make is that parsing money amounts with regexes is bad and should not be attempted at all. See also: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Ryan Bigg Oct 10 '12 at 01:06
  • 1
    I agree that your solution is best, but don't agree that regexes should never be used to parse money. In fact, the money gem uses regexes to parse money: https://github.com/collectiveidea/money/blob/master/lib/money/core_extensions.rb#L48 – Nick Colgan Oct 10 '12 at 01:32