Module: Amount::Comparison

Includes:
Comparable
Included in:
Amount
Defined in:
lib/amount/comparison.rb

Overview

Comparison, equality, hashing, and sign predicates for ‘Amount`.

Pulls in ‘Comparable` itself so consumers only need `include Comparison` to get `<`, `<=`, `>`, `>=`, `between?`, `clamp`, and `Enumerable#min`/ `#max` alongside the explicit `<=>` / `==` / `eql?` / `hash` defined here.

Instance Method Summary collapse

Instance Method Details

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

Examples:

Amount.usdc("1") <=> Amount.usdc("2")
# => -1

Parameters:

  • other (Object)

Returns:

  • (-1, 0, 1, nil)


43
44
45
46
47
48
49
50
# File 'lib/amount/comparison.rb', line 43

def <=>(other)
  return nil unless other.is_a?(Amount)

  comparable = coerce_other_to_self_type(other)
  return nil unless comparable

  @atomic <=> comparable.atomic
end

#==(other) ⇒ Boolean

Examples:

Amount.usdc("1.50") == Amount.usdc("1.50")
# => true

Parameters:

  • other (Object)

Returns:

  • (Boolean)


57
58
59
# File 'lib/amount/comparison.rb', line 57

def ==(other)
  same_type?(other) && @atomic == other.atomic
end

#eql?(other) ⇒ Boolean

Examples:

Hash-key equality keeps class and symbol identity

Amount.usdc("1").eql?(Amount.usdc("1"))
# => true

Parameters:

  • other (Object)

Returns:

  • (Boolean)


66
67
68
# File 'lib/amount/comparison.rb', line 66

def eql?(other)
  other.class == self.class && symbol == other.symbol && @atomic == other.atomic
end

#hashInteger

Examples:

{ Amount.usdc("1") => :ok }[Amount.usdc("1")]
# => :ok

Returns:

  • (Integer)


74
75
76
# File 'lib/amount/comparison.rb', line 74

def hash
  [self.class, symbol, @atomic].hash
end

#negative?Boolean

Examples:

Amount.usdc("-1").negative?
# => true

Returns:

  • (Boolean)


36
# File 'lib/amount/comparison.rb', line 36

def negative? = @atomic.negative?

#positive?Boolean

Examples:

Amount.usdc("1").positive?
# => true

Returns:

  • (Boolean)


30
# File 'lib/amount/comparison.rb', line 30

def positive? = @atomic.positive?

#same_type?(other) ⇒ Boolean

Examples:

Amount.usdc("1").same_type?(Amount.usdc("2"))
# => true

Parameters:

  • other (Object)

Returns:

  • (Boolean)


16
17
18
# File 'lib/amount/comparison.rb', line 16

def same_type?(other)
  other.is_a?(Amount) && other.symbol == symbol
end

#zero?Boolean

Examples:

Amount.usdc(0, from: :atomic).zero?
# => true

Returns:

  • (Boolean)


24
# File 'lib/amount/comparison.rb', line 24

def zero? = @atomic.zero?