Class: Integer

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_hex/integer.rb

Instance Method Summary collapse

Instance Method Details

#ceil(ndigits = 0, base: 0x10) ⇒ Object



36
37
38
# File 'lib/ruby_hex/integer.rb', line 36

def ceil(ndigits = 0, base: 0x10)
  -(-self).floor(ndigits, base: base)
end

#digits(base = 0x10) ⇒ Object



13
14
15
# File 'lib/ruby_hex/integer.rb', line 13

def digits(base = 0x10)
  _origin_digits(base)
end

#floor(ndigits = 0, base: 0x10) ⇒ Object



41
42
43
44
45
46
# File 'lib/ruby_hex/integer.rb', line 41

def floor(ndigits = 0, base: 0x10)
  return self if ndigits >= 0

  ndigits = -ndigits.to_i
  self - self % base**ndigits
end

#inspect(base: 0x10) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ruby_hex/integer.rb', line 18

def inspect(base: 0x10)
  per =
    case base
    when 0x2
      '0b'
    when 0x10
      '0x'
    when 0x8
      '0'
    when 0xa
      ''
    else
      raise ArgumentError, "base #{base} can't inspect"
    end
  "#{'-' if negative?}#{per}#{abs.to_s(base)}"
end

#round(ndigits = 0, half: :up, base: 0x10) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/ruby_hex/integer.rb', line 54

def round(ndigits = 0, half: :up, base: 0x10)
  return self if ndigits >= 0

  ndigits = ndigits.to_i
  half = :up if half.nil?
  n = self % base**-ndigits / base**(-ndigits - 0x1)
  case n <=> (base / 0x2)
  when -1
    floor(ndigits, base: base)
  when 1
    ceil(ndigits, base: base)
  when 0
    case half
    when :up
      (negative? ? -1 : 1) * abs.ceil(ndigits, base: base)
    when :down
      truncate(ndigits, base: base)
    when :even
      fl = floor(ndigits, base: base)
      if (fl % base**(-ndigits + 0x1) / base**-ndigits).even?
        fl
      else
        ceil(ndigits, base: base)
      end
    else
      raise ArgumentError, "invalid rounding mode: #{half}"
    end
  end
end

#to_s(base = 0x10) ⇒ Object



8
9
10
# File 'lib/ruby_hex/integer.rb', line 8

def to_s(base = 0x10)
  _origin_to_s(base)
end

#truncate(ndigits = 0, base: 0x10) ⇒ Object



49
50
51
# File 'lib/ruby_hex/integer.rb', line 49

def truncate(ndigits = 0, base: 0x10)
  (negative? ? -0x1 : 0x1) * abs.floor(ndigits, base: base)
end