Class: Zold::Amount

Inherits:
Object
  • Object
show all
Defined in:
lib/zold/amount.rb

Overview

Amount

Constant Summary collapse

ZERO =
Amount.new(coins: 0)

Instance Method Summary collapse

Constructor Details

#initialize(coins: nil, zld: nil) ⇒ Amount

Returns a new instance of Amount.



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/zold/amount.rb', line 30

def initialize(coins: nil, zld: nil)
  if !coins.nil?
    raise "Integer is required, while #{coins.class} provided: #{coins}" unless coins.is_a?(Integer)
    @coins = coins
  elsif !zld.nil?
    raise "Float is required, while #{zld.class} provided: #{zld}" unless zld.is_a?(Float)
    @coins = (zld * 2**24).to_i
  else
    raise 'You can\'t specify both coints and zld'
  end
end

Instance Method Details

#*(other) ⇒ Object



99
100
101
102
103
# File 'lib/zold/amount.rb', line 99

def *(other)
  c = (@coins * other).to_i
  raise "Overflow, can't multiply #{@coins} by #{m}" if c > 2**63
  Amount.new(coins: c)
end

#+(other) ⇒ Object



81
82
83
84
# File 'lib/zold/amount.rb', line 81

def +(other)
  raise '+ may only work with Amount' unless other.is_a?(Amount)
  Amount.new(coins: @coins + other.to_i)
end

#-(other) ⇒ Object



86
87
88
89
# File 'lib/zold/amount.rb', line 86

def -(other)
  raise '- may only work with Amount' unless other.is_a?(Amount)
  Amount.new(coins: @coins - other.to_i)
end

#<(other) ⇒ Object



71
72
73
74
# File 'lib/zold/amount.rb', line 71

def <(other)
  raise '< may only work with Amount' unless other.is_a?(Amount)
  @coins < other.to_i
end

#<=(other) ⇒ Object



76
77
78
79
# File 'lib/zold/amount.rb', line 76

def <=(other)
  raise '<= may only work with Amount' unless other.is_a?(Amount)
  @coins <= other.to_i
end

#==(other) ⇒ Object



61
62
63
64
# File 'lib/zold/amount.rb', line 61

def ==(other)
  raise '== may only work with Amount' unless other.is_a?(Amount)
  @coins == other.to_i
end

#>(other) ⇒ Object



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

def >(other)
  raise '> may only work with Amount' unless other.is_a?(Amount)
  @coins > other.to_i
end

#negative?Boolean

Returns:

  • (Boolean)


95
96
97
# File 'lib/zold/amount.rb', line 95

def negative?
  @coins < 0
end

#to_iObject



44
45
46
# File 'lib/zold/amount.rb', line 44

def to_i
  @coins
end

#to_sObject



52
53
54
55
56
57
58
59
# File 'lib/zold/amount.rb', line 52

def to_s
  text = "#{to_zld}ZLD"
  if negative?
    Rainbow(text).red
  else
    Rainbow(text).green
  end
end

#to_zldObject



48
49
50
# File 'lib/zold/amount.rb', line 48

def to_zld
  format('%0.2f', @coins.to_f / 2**24)
end

#zero?Boolean

Returns:

  • (Boolean)


91
92
93
# File 'lib/zold/amount.rb', line 91

def zero?
  @coins.zero?
end