money
money copied to clipboard
Comparison between two currencies (greater/less than)
Can I compare two objects in different currencies? I've searched throug the issues and found only this thread. Where only equality is discussed.
I wonder if understanding which on is greater/less is useful (seems so).
rub = Money.new(75_00, 'RUB')
usd = Money.new(1_00, 'USD')
Money.add_rate("USD", "RUB", 74.90)
usd < rub
Traceback (most recent call last):
5: from /home/install/.rvm/rubies/ruby-2.7.2/bin/irb:23:in `<main>'
4: from /home/install/.rvm/rubies/ruby-2.7.2/bin/irb:23:in `load'
3: from /home/install/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/irb-1.2.6/exe/irb:11:in `<top (required)>'
2: from (irb):13
1: from (irb):13:in `<'
ArgumentError (comparison of Money with Money failed)
The current behaviour is when you compare USD with RUB. The code converts the RUB to USD and than compare USD to USD. The reason you are seeing the above exception is because it is not possible to convert RUB to USD. You need to add the rate for RUB to USD eg. `Money.add_rate("RUB", "USD", 0.013) so that RUB is converted to USD and the comparison works.
The modified code as follows below: rub = Money.new(75_00, 'RUB') usd = Money.new(1_00, 'USD') Money.add_rate("RUB", "USD", 0.013) usd < rub => false
I hope this helps and please let me know if you have any other questions. Thank you.
one quick follow-up, the reason is does not intuit the reverse is that currencies do not always covert between each other consistently. Most of the time it does, but when it does not, it causes severe issues,