Class: Integer

Inherits:
Object show all
Defined in:
lib/lite/ruby/integer.rb

Instance Method Summary collapse

Instance Method Details

#bit(bit) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/lite/ruby/integer.rb', line 11

def bit(bit)
  if bit.negative?
    mask = (1 << ~bit)
    self & ~mask
  else
    mask = (1 << bit)
    self | mask
  end
end

#bit?(bit) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
# File 'lib/lite/ruby/integer.rb', line 21

def bit?(bit)
  mask = (1 << bit)
  (self & mask) != 0
end

#bit_clear(bit) ⇒ Object



26
27
28
29
# File 'lib/lite/ruby/integer.rb', line 26

def bit_clear(bit)
  mask = (1 << bit)
  self & ~mask
end

#bitmask(mask) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/lite/ruby/integer.rb', line 31

def bitmask(mask)
  if mask.negative?
    self & mask
  else
    self | mask
  end
end

#bitmask?(mask) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/lite/ruby/integer.rb', line 39

def bitmask?(mask)
  (self & mask) != 0
end

#combinatorial(num) ⇒ Object



43
44
45
# File 'lib/lite/ruby/integer.rb', line 43

def combinatorial(num)
  (0...num).inject(1) { |acc, i| (acc * (self - i)) / (i + 1) }
end

#factorialObject



47
48
49
# File 'lib/lite/ruby/integer.rb', line 47

def factorial
  (1..self).inject { |acc, i| acc * i } || 0
end

#factorsObject



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/lite/ruby/integer.rb', line 51

def factors
  limit = Math.sqrt(self).floor

  (1..limit).each_with_object([]) do |i, array|
    next unless (self % i).zero?

    sq = (self / i)
    array.push(i)
    array.push(sq) if sq != i
  end
end

#of(&block) ⇒ Object



63
64
65
# File 'lib/lite/ruby/integer.rb', line 63

def of(&block)
  Array.new(self, &block)
end

#roman_numeralObject



67
68
69
70
71
72
# File 'lib/lite/ruby/integer.rb', line 67

def roman_numeral
  return '' if zero?
  return "-#{(-self).roman_numeral}" if negative?

  ROMAN_NUMERALS.each { |key, val| break "#{key}#{(self - val).roman_numeral}" if val <= self }
end

#to_timeObject Also known as: to_t



74
75
76
# File 'lib/lite/ruby/integer.rb', line 74

def to_time
  Time.at(self)
end