Method: Money#<=>

Defined in:
lib/money/money.rb

#<=>(other_money) ⇒ -1, ...

Compares this money object against another object. other_money must respond to #to_money. Returns -1 when less than, 0 when equal and 1 when greater than.

If other_money is a different currency, then other_money will first be converted into this money object’s currency by calling #exchange on other_money.

Comparisons against objects that do not respond to #to_money will cause an ArgumentError to be raised.

Examples:

Money.new(100) <=> 99             #=>  1
Money.new(100) <=> Money.new(100) #=>  0
Money.new(100) <=> "$101.00"      #=> -1

Parameters:

Returns:

  • (-1, 0, 1)

Raises:

  • (ArgumentError)


495
496
497
498
499
500
501
502
503
504
505
506
# File 'lib/money/money.rb', line 495

def <=>(other_money)
  if other_money.respond_to?(:to_money)
    other_money = other_money.to_money
    if self.currency == other_money.currency
      cents <=> other_money.cents
    else
      cents <=> other_money.exchange_to(currency).cents
    end
  else
    raise ArgumentError, "Comparison of #{self.class} with #{other_money.inspect} failed"
  end
end