Class: Code::Object::Integer

Inherits:
Number show all
Defined in:
lib/code/object/integer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Code::Object

#<=>, #==, #[], #[]=, #falsy?, #hash, #key?, #truthy?

Constructor Details

#initialize(whole, exponent: nil) ⇒ Integer

Returns a new instance of Integer.



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/code/object/integer.rb', line 6

def initialize(whole, exponent: nil)
  @raw = whole.to_i

  if exponent
    if exponent.is_a?(::Code::Object::Number)
      @raw = @raw * 10**exponent.raw
    else
      raise ::Code::Error::TypeError.new("exponent is not a number")
    end
  end
end

Instance Attribute Details

#rawObject (readonly)

Returns the value of attribute raw.



4
5
6
# File 'lib/code/object/integer.rb', line 4

def raw
  @raw
end

Instance Method Details

#+(other) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/code/object/integer.rb', line 41

def +(other)
  if other.is_a?(::Code::Object::Integer)
    ::Code::Object::Integer.new(raw + other.raw)
  elsif other.is_a?(::Code::Object::Decimal)
    ::Code::Object::Decimal.new(raw + other.raw)
  else
    raise ::Code::Error::TypeError
  end
end

#call(**args) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/code/object/integer.rb', line 18

def call(**args)
  operator = args.fetch(:operator, nil)
  arguments = args.fetch(:arguments, [])

  if operator == "even?"
    even?(arguments)
  elsif operator == "to_string"
    code_to_s(arguments)
  elsif operator == "*"
    multiplication(arguments)
  elsif operator == "/"
    division(arguments)
  elsif %w[% - + **].detect { |o| operator == o }
    integer_or_decimal_operation(operator.to_sym, arguments)
  elsif %w[> >= < <=].detect { |o| operator == o }
    comparaison(operator.to_sym, arguments)
  elsif %w[<< >> & | ^].detect { |o| operator == o }
    integer_operation(operator.to_sym, arguments)
  else
    super
  end
end

#inspectObject



59
60
61
# File 'lib/code/object/integer.rb', line 59

def inspect
  to_s
end

#succObject



51
52
53
# File 'lib/code/object/integer.rb', line 51

def succ
  ::Code::Object::Integer.new(raw + 1)
end

#to_sObject



55
56
57
# File 'lib/code/object/integer.rb', line 55

def to_s
  raw.to_s
end