Integer
Integer
Integer 객체는 정수 값을 나타내요. 정수 리터럴로 만들 수도 있고, Integer 메서드로 특정 객체를 정수로 변환할 수도 있어요. 이 클래스의 인스턴스에 싱글톤 메서드를 추가하려 하면 예외가 나요.
출처: Ruby 4.0 API
본문
정수는 Ruby에서 가장 기본적인 타입이지만, 메서드가 아주 많아서 한눈에 정리해 두면 좋아요. Integer는 Numeric과 Object를 상속하고 Comparable 모듈을 포함해요.
여기서 정리할 메서드들을 크게 네 묶음으로 나눌게요: 질의(Querying), 비교(Comparing), 변환(Converting), 기타(Other).
질의 (Querying)
allbits?(mask)—mask에 설정된(=1) 모든 비트가self에도 설정돼 있으면true.anybits?(mask)—mask에 설정된 비트 중 하나라도self에 설정돼 있으면true.nobits?(mask)—mask에 설정된 비트가self에 하나도 없으면true.
비교 (Comparing)
<,<=,<=>,==(별칭===),>,>=— 비교 연산자들.
변환 (Converting)
::sqrt— 주어진 값의 정수 제곱근.::try_convert— 주어진 값을 Integer로 변환.%(별칭modulo),&,*,**,+,-,/,<<,>>,[],^,|— 산술·비트 연산들.ceil,chr,digits,div,divmod,fdiv,floor,pow,pred,remainder,round,succ(별칭next),to_f,to_s(별칭inspect),truncate.
기타 (Other)
downto,times,upto— 범위 반복 메서드들.
상수 (Constants)
GMP_VERSION— 로드된 GMP의 버전.
클래스 메서드
sqrt(numeric) → integer
음이 아닌 정수 n의 정수 제곱근을 돌려줘요. 곧 numeric의 제곱근보다 작거나 같은 가장 큰 음이 아닌 정수예요.
Integer.sqrt(0) # => 0
Integer.sqrt(1) # => 1
Integer.sqrt(24) # => 4
Integer.sqrt(25) # => 5
Integer.sqrt(10**400) # => 10**200
numeric이 Integer가 아니면 Integer로 변환해요. 이 메서드는 Math.sqrt(numeric).floor와 동등한데, 후자는 부동소수점의 한정된 정밀도 때문에 참값과 달라질 수 있어요.
Integer.sqrt(10**46) # => 100000000000000000000000
Math.sqrt(10**46).floor # => 99999999999999991611392
numeric이 음수면 예외가 나요.
try_convert(object) → object, integer, or nil
object가 Integer면 object를 돌려줘요. 아니고 object가 :to_int에 응답하면 object.to_int를 호출해 결과를 돌려줘요. :to_int에 응답하지 않으면 nil. object.to_int가 Integer를 돌려주지 않으면 예외예요.
Integer.try_convert(1) # => 1
Integer.try_convert(1.25) # => 1
Integer.try_convert() # => nil
인스턴스 메서드 — 산술 연산자
self % other → real_numeric
self를 other로 나눈 나머지를 실수 numeric(Integer, Float, Rational)으로 돌려줘요. modulo의 별칭이에요.
10 % 3 # => 1
10 % -3 # => -2
10 % 3.0 # => 1.0
나눗셈에서 나머지의 부호는 나누는 수(divisor)를 따르는 점(10 % -3이 -2)을 기억해 두면 좋아요.
self & other → integer
비트 AND. self와 other의 대응 비트가 둘 다 1일 때만 결과 비트가 1이에요.
self * other → numeric
self ** exponent → numeric
self + other → numeric
self - other → numeric
- self → integer
self / other → numeric
각각 곱·거듭제곱·합·차·부호 바꾸기·나눗셈이에요. 정수 other로 나누면 결과를 정수로 버리고, 비-정수 other면 비-정수 결과를 돌려줘요.
4 / 3 # => 1
4 / -3 # => -2
4 / 3.0 # => 1.3333333333333333
4 / Rational(3, 1) # => (4/3)
self < other → true or false
self <= other → true or false
self <=> other → -1, 0, 1, or nil
self == other → true or false
self > other → true or false
self >= real → true or false
비교 연산자들이에요. <=>는 self가 작으면 -1, 같으면 0, 크면 1, 비교 불가면 nil을 돌려줘요. ==는 수치적으로 같으면 true(예: 1 == 1.0은 true). Comparable 모듈의 각 메서드는 Integer#<=>를 비교에 사용해요.
self << count → integer
self >> count → integer
비트를 왼쪽/오른쪽으로 count만큼 시프트해요. count가 음수면 반대 방향으로 시프트돼요.
n = 0b11110000
"%08b" % (n << 1) # => "111100000"
"%08b" % (n >> 1) # => "01111000"
self[offset] → 0 or 1
self[offset, size] → integer
self[range] → integer
self에서 비트 조각을 돌려줘요. offset만 주면 그 위치의 비트(offset 0이 최하위 비트)를 돌려줘요. n[i]는 (n >> i) & 1과 동등해서 음수 인덱스는 항상 0이에요. offset, size나 range를 주면 offset부터 시작해 상위 비트 방향으로 그만큼의 비트를 돌려줘요.
self ^ other → integer
비트 EXCLUSIVE OR. self와 other의 대응 비트가 서로 다를 때만 결과 비트가 1이에요.
self | other → integer
비트 OR. 어느 한쪽이라도 1이면 결과 비트가 1이에요.
~int → integer
일의 보수(one's complement). self의 각 비트를 뒤집어요. 정수는 개념적으로 무한 길이라 왼쪽에 1비트가 무한히 있는 것처럼 동작해요. 16진수 표기에서 왼쪽에 두 개의 점(기호)으로 보여요.
sprintf("%X", ~0x1122334455) # => "..FEEDDCCBBAA"
인스턴스 메서드 — 그 외
abs → integer
self의 절댓값을 돌려줘요. magnitude의 별칭이에요.
allbits?(mask) → true or false
anybits?(mask) → true or false
nobits?(mask) → true or false
비트 마스크 관련 질의 메서드들이에요. allbits?는 mask의 모든 1비트가 self에 있으면 true, anybits?는 하나라도 있으면 true, nobits?는 하나도 없으면 true예요.
bit_length → integer
self 값의 비트 수를 돌려줘요. 부호 비트와 다른 최상위 비트의 위치(최하위 비트가 위치 1)예요. 그런 비트가 없으면(0이나 -1) 0을 돌려줘요. ceil(log2(self < 0 ? -self : self + 1))과 같아요. Array#pack에서 오버플로 검출에 쓸 수 있어요.
ceil(ndigits = 0) → integer
ndigits에 따른 "ceiling" 값을 돌려줘요. self가 0이면 0, 0이 아니고 ndigits가 음이 아니면 self. ndigits가 음수면 10 ** ndigits.abs 단위로 계산한, self보다 크거나 같은 가장 작은 배수예요.
ceildiv(numeric) → integer
self를 numeric으로 나눈 결과를 가장 가까운 정수로 올림해요.
3.ceildiv(3) # => 1
4.ceildiv(3) # => 2
chr → string
chr(encoding) → string
주어진 encoding에 따라 self 값이 나타내는 문자가 담긴 1-문자 문자열을 돌려줘요. 65.chr # => "A". self가 음수면 예외예요. Integer#ord와 관련돼요.
coerce(numeric) → array
numeric과 int를 모두 Integer나 Float 객체로 나타낸 배열을 돌려줘요. numeric을 Integer나 Float로 변환해서 만들어요. numeric이 Integer나 Float 타입이 아니면 TypeError가 나요.
denominator → 1
항상 1을 돌려줘요.
digits(base = 10) → array_of_integers
base-진법에서의 self 자릿수를 나타내는 정수 배열을 돌려줘요. 배열의 첫 요소가 최하위 자릿수예요.
12345.digits # => [5, 4, 3, 2, 1]
12345.digits(7) # => [4, 6, 6, 0, 5]
12345.digits(100) # => [45, 23, 1]
self가 음수거나 base가 2 미만이면 예외예요.
div(numeric) → integer
정수 나눗셈. self를 numeric으로 나눈 정수 결과를 돌려줘요.
divmod(other) → array
[q, r] 2-요소 배열을 돌려줘요. q = (self/other).floor(몫), r = self % other(나머지)예요.
downto(limit) {|i| ... } → self
downto(limit) → enumerator
self부터 limit까지 각 정수 값으로 블록을 호출하고 self를 돌려줘요. 블록이 없으면 Enumerator를 돌려줘요.
even? → true or false
self가 짝수면 true, 아니면 false.
fdiv(numeric) → float
self를 numeric으로 나눈 Float 결과를 돌려줘요.
floor(ndigits = 0) → integer
ndigits에 따른 "floor" 값을 돌려줘요. 형태는 ceil의 반대예요. ndigits가 음수면 self보다 작거나 같은 가장 큰 배수를 돌려줘요.
gcd(other_int) → integer
두 정수의 최대공약수를 돌려줘요. 결과는 항상 양수예요. 0.gcd(x)와 x.gcd(0)는 x.abs를 돌려줘요.
36.gcd(60) #=> 12
gcdlcm(other_int) → array
[gcd, lcm] — 두 정수의 최대공약수와 최소공배수 배열을 돌려줘요.
inspect
to_s의 별칭이에요.
integer? → true
self는 이미 Integer니 항상 true를 돌려줘요.
lcm(other_int) → integer
두 정수의 최소공배수를 돌려줘요. 결과는 항상 양수예요. 0.lcm(x)와 x.lcm(0)는 0을 돌려줘요.
magnitude
abs의 별칭이에요. modulo는 %의, next는 succ의 별칭이에요.
numerator → self
self를 돌려줘요.
odd? → true or false
self가 홀수면 true, 아니면 false.
ord → self
self를 돌려줘요. Ruby 1.9의 문자 리터럴과의 호환을 위한 거예요.
pow(numeric) → numeric
pow(integer, integer) → integer
(모듈러) 거듭제곱을 돌려줘요.
a.pow(b) #=> same as a**b
a.pow(b, m) #=> same as (a**b) % m, but avoids huge temporary values
pred → next_integer
self의 이전 정수(self - 1과 동등)를 돌려줘요.
rationalize([eps]) → rational
값을 유리수로 돌려줘요. 선택 인자 eps는 항상 무시돼요.
remainder(other) → real_number
self를 other로 나눈 나머지를 돌려줘요. %와 달리 나머지의 부호가 self를 따라요.
11.remainder(4) # => 3
-11.remainder(4) # => -3
round(ndigits= 0, half: :up) → integer
ndigits 소수 자릿수 정밀도로 가장 가까운 값에 반올림한 self를 돌려줘요. ndigits가 음수면 결과에 ndigits.abs개의 끝자리 0이 있어요. half: 키워드 인자는 후보 두 값의 정중앙에 있을 때 반올림 방식을 정해요(:up, :down, :even).
555.round(-1) # => 560
555.round(-2) # => 600
25.round(-1, half: :up) # => 30
25.round(-1, half: :down) # => 20
25.round(-1, half: :even) # => 20
size → integer
self의 머신 표현(machine representation)에서의 바이트 수를 돌려줘요. 값은 시스템에 의존해요.
succ → next_integer
self의 다음 정수(self + 1과 동등)를 돌려줘요. next의 별칭이에요.
times {|i| ... } → self
times → enumerator
블록을 self번 호출하면서 각 정수를 (0..self-1)로 넘겨요. 블록이 없으면 Enumerator.
to_bn()
Integer를 OpenSSL::BN으로 캐스팅해요.
to_f → float
self를 Float로 변환해요. 값이 Float에 안 맞으면 결과가 Infinity예요.
to_i → self
to_int → self
self(이미 Integer)를 돌려줘요.
to_r → rational
값을 유리수로 돌려줘요.
to_s(base = 10) → string
진법 base(2..36)에서의 self의 자릿값 표현 문자열을 돌려줘요. base가 범위를 벗어나면 예외예요. inspect의 별칭이에요.
12345.to_s(2) # => "11000000111001"
12345.to_s(16) # => "3039"
78546939656932.to_s(36) # => "rubyrules"
truncate(ndigits = 0) → integer
ndigits 소수 자릿수 정밀도로 0 방향으로 버린 self를 돌려줘요. ndigits가 음수면 결과에 ndigits.abs개의 끝자리 0이 있어요.
555.truncate(-1) # => 550
555.truncate(-2) # => 500
upto(limit) {|i| ... } → self
upto(limit) → enumerator
self부터 limit까지 각 정수 값으로 블록을 호출하고 self를 돌려줘요.
zero? → true or false
self가 0이면 true, 아니면 false.