Created
April 11, 2025 01:19
-
-
Save tota1099/1d3cc32eaf0fcd133f3c3d678a8f6387 to your computer and use it in GitHub Desktop.
currency_conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit' | |
extend Test::Unit::Assertions | |
CONVERSIONS = { | |
'USD' => { | |
'BRL' => 5, | |
'AJU' => 3 | |
}, | |
'MXN' => { 'ARS' => 3 }, | |
'BRL' => { 'MXN' => 2, 'XXX' => 2 }, | |
'ARS' => { 'BPN' => 0.5, 'XXX' => 0.5 } | |
} | |
def convert(unit, origin_currency, conversion_currency) | |
return -1 unless CONVERSIONS[origin_currency] | |
rate = CONVERSIONS[origin_currency][conversion_currency] | |
return rate * unit if rate | |
CONVERSIONS[origin_currency].keys.each do |currency| | |
rate_deep = convert(unit, currency, conversion_currency) | |
return rate_deep * CONVERSIONS[origin_currency][currency] if rate_deep != -1 | |
end | |
return -1 | |
end | |
assert_equal convert(3, 'USD', 'BRL'), 15 | |
assert_equal convert(3, 'USD', 'XD'), -1 | |
assert_equal convert(3, 'XD', 'USD'), -1 | |
assert_equal convert(3, 'USD', 'MXN'), 30 | |
assert_equal convert(3, 'USD', 'ARS'), 90 | |
assert_equal convert(3, 'USD', 'BPN'), 45 | |
assert_equal convert(3, 'USD', 'XXX'), 30 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment