Class: Integer

Inherits:
Object show all
Includes:
Random::IntegerExtensions
Defined in:
lib/core/facets/roman.rb,
lib/core/facets/integer/of.rb,
lib/standard/facets/random.rb,
lib/core/facets/integer/bitmask.rb,
lib/core/facets/integer/ordinal.rb,
lib/core/facets/integer/to_base.rb,
lib/core/facets/integer/multiple.rb,
lib/core/facets/integer/factorial.rb

Instance Method Summary collapse

Methods included from Random::IntegerExtensions

#random_delta

Instance Method Details

#bit(bit) ⇒ Object

Set a bit.

0.bit(4)  #=> 16

Using a negative figure will clear a bit.

10.bit(-4)      #=> 2

This is more easily seen using binary.

0b0100.bit(-3)  #=> 0

CREDIT: Thomas Sawyer, George Moschovitis



17
18
19
20
21
22
23
24
25
# File 'lib/core/facets/integer/bitmask.rb', line 17

def bit(bit)
  if bit < 0
    mask = (1 << ~bit)
    self & ~mask
  else
    mask = (1 << bit)
    self | mask
  end
end

#bit?(bit) ⇒ Boolean

Is a bit set?

8.bit?(3)  #=> true
8.bit?(2)  #=> false

CREDIT: Thomas Sawyer, George Moschovitis

Returns:

  • (Boolean)


43
44
45
46
# File 'lib/core/facets/integer/bitmask.rb', line 43

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

#bit_clear(bit) ⇒ Object

Clear bit.

CREDIT: George Moschovitis



31
32
33
34
# File 'lib/core/facets/integer/bitmask.rb', line 31

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

#bitmask(mask) ⇒ Object

Apply a bitmask.

1.bitmask(6) #=> 7

Using a inverted bitmask clears bits.

7.bitmask(~2) #=> 5
5.bitmask(~2) #=> 5

CREDIT: George Moschovitis



59
60
61
62
63
64
65
# File 'lib/core/facets/integer/bitmask.rb', line 59

def bitmask(mask)
  if mask < 0
    self & mask
  else
    self | mask
  end
end

#bitmask?(mask) ⇒ Boolean

Is bitmask set?

7.bitmask?(7) #=> true
7.bitmask?(5) #=> true
8.bitmask?(3) #=> false

CREDIT: George Moschovitis

Returns:

  • (Boolean)


75
76
77
# File 'lib/core/facets/integer/bitmask.rb', line 75

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

#factorial ⇒ Object Also known as: fac

Calculate the factorial of an integer.

2.factorial  #=> 2
3.factorial  #=> 6
4.factorial  #=> 24

CREDIT: Malte Milatz



11
12
13
14
15
16
# File 'lib/core/facets/integer/factorial.rb', line 11

def factorial
  return 1 if zero?
  f = 1
  2.upto(self) { |n| f *= n }
  f
end

#multiple?(number) ⇒ Boolean

Is self a multiple of a given number?

7.multiple?(2)  #=> false
8.multiple?(2)  #=> true

CREDIT: Trans

Returns:

  • (Boolean)


10
11
12
13
14
15
16
# File 'lib/core/facets/integer/multiple.rb', line 10

def multiple?(number)
  if number.zero?
    zero? ? true : false
  else
    self % number == 0
  end
end

#of(&block) ⇒ Object Also known as: times_collect, times_map

Like #times but returns a collection of the yield results.

a = 3.of { |i| "#{i+1}" }
a #=> [ "1", "2", "3" ]


9
10
11
# File 'lib/core/facets/integer/of.rb', line 9

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

#ordinal ⇒ Object Also known as: ordinalize

The number with its English ordinal suffix.

1.ordinal    #=> "1st"
12.ordinal   #=> "12th"
103.ordinal  #=> "103rd"
-1.ordinal   #=> "-1st"


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/core/facets/integer/ordinal.rb', line 10

def ordinal
  n = abs % 100
  suffix =
    if (11..13).include?(n)
      'th'
    else
      case n % 10
      when 1 then 'st'
      when 2 then 'nd'
      when 3 then 'rd'
      else 'th'
      end
    end
  "#{self}#{suffix}"
end

#roman ⇒ Object

Converts this integer to a roman numeral.

NOTE: This method is not a common core extension and is not loaded automatically when using require 'facets'.



31
32
33
34
35
36
37
38
39
# File 'lib/core/facets/roman.rb', line 31

def roman
  int = self
  #return nil if integer > ROMAN_MAX
  return "-#{(-int).roman}" if int < 0
  return "" if int == 0
  ROMAN_VALUES.each do |(i, v)|
    return(i + (int-v).roman) if v <= int 
  end
end

#to_base(base) ⇒ Object

Converts the integer to a string in any base from 2 to 62, or with a custom set of digits.

Ruby's own to_s(base) stops at base 36. Above that, the digits are 0-9, then a-z, then A-Z. Up to base 36, the result is the same as to_s(base).

255.to_base(16)              #=> "ff"
255.to_base(62)              #=> "47"
809145531659995.to_base(62)  #=> "3HLszsQsP"
-255.to_base(62)             #=> "-47"

To use other digits, give them as a string, starting with the digit for zero. The number of digits is the base.

37.to_base("OLTWFS")         #=> "LOL"

In base 256 the digits are bytes, so the result is the number's bytes, most significant first, as a binary string.

256.to_base(256)             #=> "\x01\x00"
0.to_base(256)               #=> "\x00"

Combining the two encodes binary data, as with Base58:

b58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
"hello".from_base(256).to_base(b58)    #=> "Cn8eVZg"
"Cn8eVZg".from_base(b58).to_base(256)  #=> "hello"

This goes through a number, so leading zero bytes are lost: "\x00hi" comes back as "hi". Formats such as Bitcoin's Base58 keep them with their own rules, which this doesn't follow.

A negative number gets a leading "-", unless "-" is one of the digits, in which case it raises ArgumentError. That includes base 256, where "-" is byte 45.

Given an array, the result is an array, with one element for each digit, most significant first. An array holding one number is a base, of any size from 2 up, and the result is the digit values:

1000.to_base([100])          #=> [10, 0]
256.to_base([256])           #=> [1, 0]
255.to_base([16])            #=> [15, 15]

Any other array is the digits themselves, starting with the digit for zero. They can be any objects:

37.to_base(%w[O L T W F S])       #=> ["L", "O", "L"]
37.to_base(%w[O L T W F S]).join  #=> "LOL"
5.to_base([:zero, :one])          #=> [:one, :zero, :one]

An array can't show a sign, so a negative number raises ArgumentError.

String#from_base converts a string back, and Array#from_base an array.

Since: 4.2.0



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/core/facets/integer/to_base.rb', line 63

def to_base(base)
  case base
  when ::Integer
    if base == 256
      if negative?
        raise ArgumentError, "can't show a negative number in base 256, where '-' is a digit"
      end
      hex = to_s(16)
      hex = "0#{hex}" if hex.size.odd?
      return [hex].pack('H*')
    end
    unless base >= 2 && base <= 62
      hint = base > 62 ? "; for digit values use to_base([#{base}])" : ""
      raise ArgumentError, "invalid radix #{base}#{hint}"
    end
    return to_s(base) if base <= 36
    digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[0, base]
  when ::String
    digits = base.chars
    if digits.size < 2
      raise ArgumentError, "a base needs at least two digits"
    end
    if digits.uniq.size < digits.size
      raise ArgumentError, "digits must not repeat"
    end
    if negative? && digits.include?('-')
      raise ArgumentError, "can't show a negative number when '-' is a digit"
    end
    digits = base
  when ::Array
    if negative?
      raise ArgumentError, "can't show a negative number as an array"
    end
    if base.size == 1 && base.first.is_a?(::Integer)
      raise ArgumentError, "invalid radix #{base.first}" if base.first < 2
      return digits(base.first).reverse
    end
    if base.size < 2
      raise ArgumentError, "a base needs at least two digits"
    end
    if base.uniq.size < base.size
      raise ArgumentError, "digits must not repeat"
    end
    return digits(base.size).reverse.map { |d| base[d] }
  else
    raise TypeError, "base must be an Integer, String or Array, not #{base.class}"
  end

  s = abs.digits(digits.size).reverse.map { |d| digits[d] }.join
  negative? ? "-#{s}" : s
end