Integer

整数的抽象类,子类有 FixnumBignum。这两种类型的整数会自动根据它们的值相互转化。在位运算中,整数可以当做无限长的位串来处理。

超类

方法

self[nth]

若是整数的第 nth 位(LSB ─ 最低意义位 ─ 是第 0 位)是 1 就返回 1,否则返回 0。

self[nth]=bit 不是 Integer 方法,因为与 Numeric 有关的类都是不可变的。

self + other
self - other
self * other
self / other
self % other
self ** other

数学运算符。分别计算:和(加)、差(减)、积(乘)、商(除)、余(模数计算)、幂(指数计算)。

self <=> other

比较 other 与 self;若是 self 大于 other 则返回正整数、若是 self 等于 other 则返回 0、若是 self 小于 other 则返回负整数。

self == other
self < other
self <= other
self > other
self >= other

比较运算符。

~ self
self | other
self & other
self ^ other

位运算符。分别计算位的逻辑非、逻辑或、逻辑与、逻辑异或。

self << bits
self >> bits

移动运算符,将位左移或右移。

符号位(MSB ─ 最大意义位)在右移时会保留。

chr

返回在字符表中数字对应的 1 位字符串。举例来说:65.chr 返回 "A"。

使用这个方法的整数必须在 0~255的范围内。超出此范围的整数会抛出 RangeError 异常。

downto(min) {|n| ... }

自 self 迭代至 min,依次迭减 1。若 self < min,则什么都不做。

参看 upto, steptimes

next
succ

返回整数的「下」一个值。

step(limit, step) {|n| ... }

从 self 依次计算区块,每次增加 step直到 limitstep 可以是负数。

step 设为 0 时,抛出 ArgumentError 异常。

返回 self。

参看 upto, downtotimes

times {|n| ... }

依次迭代执行 self 次,从 0 至 self-1。若 self 为负数,则什么都不做。

返回 self。

参看 upto, downtostep

to_f

将数值转换成浮点数(Float)。

to_s([base])

将整数转为 10 进制的字符串表达式。

若是指定了参数,则会进行 base 进制的转换。若 base 超出 2~36 的范围,会抛出 ArgumentError 异常。

p 10.to_s(2)    # => "1010"
p 10.to_s(8)    # => "12"
p 10.to_s(16)   # => "a"
p 35.to_s(36)   # => "z"
upto(max) {|n| ... }

自 self 迭代至 max,依次迭加 1。若 self > max,则什么都不做。

返回 self。

参看 downto, steptimes