Ruby/Справочник/Fixnum: различия между версиями

Содержимое удалено Содержимое добавлено
Нет описания правки
Нет описания правки
Строка 1:
==Класс Fixnum < Integer==
Класс <tt>Fixnum</tt> - это целые числа (<tt>Integer</tt>), которые умещаются в одно машинное слово (минус 1 бит). Если в результате какой либо операции число класса <tt>Fixnum</tt> выходит за пределы этого диапазона, то значение автоматически преобразуется к классу [[Ruby/Справочник/Bignum|Bignum]].
A <tt>Fixnum</tt> holds <tt>Integer</tt> values that can be represented in a native machine word (minus 1 bit). If any operation on a <tt>Fixnum</tt> exceeds this range, the value is automatically converted to a <tt>Bignum</tt>.
Объекты класса <tt>Fixnum</tt> имеют непосредственное значение. Это значит, что, когда они присваиваются или передаются в качестве параметра, происходит передача фактического объекта, не не ссылки. Присваивание не работает с ссылками на объекты <tt>Fixnum</tt>. Существует лишь один объект <tt>Fixnum</tt> для каждого целочисленного значения. Именно поэтому вы не можете добавить метод-одиночку для объекта <tt>Fixnum</tt>.
<tt>Fixnum</tt> objects have immediate value. This means that when they are assigned or passed as parameters, the actual object is passed, rather than a reference to that object. Assignment does not alias <tt>Fixnum</tt> objects. There is effectively only one <tt>Fixnum</tt> object instance for any given integer value, so, for example, you cannot add a singleton method to a <tt>Fixnum</tt>.
----
 
Строка 23:
<source lang=ruby>Fixnum.induced_from(obj) #-> fixnum</source>
----
Преобразует ''obj'' в объект класса <tt>Fixnum</tt>. Работает с [[Ruby/Справочник/Numeric|числовыми]] параметрами. Еще работает с [[Ruby/Справочник/Symbol|символами]], но рекомендуется не использовать данную возможность.
Convert <tt>obj</tt> to a Fixnum. Works with numeric parameters. Also works with Symbols, but this is deprecated.
===Fixnum#%===
----
<source lang=ruby>fix % other #-> Numericnumeric
fix.modulo(other) #-> Numericnumeric</source>
----
Возвращает остаток от деления числа ''fix'' на число''other''.
Returns <tt>fix</tt> modulo <tt>other</tt>. See <tt>Numeric.divmod</tt> for more information.
<source lang=ruby>5 % 2 #-> 1
5 % -2 #-> -1
5 % -2.2 #-> -1.6</source>
{{info|Полезно взглянуть в описание метода [[Ruby/Справочник/Numeric#Numeric#divmod|Numeric#divmod]] для получения более детальной информации}}
{{Идентичные методы|Fixnum|%|modulo}}
{{Похожие методы|Fixnum|**|+|-|/|*}}
===Fixnum#&===
----
<source lang=ruby>fix & other #-> integer</source>
----
Побитовое <tt>И</tt>.
Bitwise AND.
===Fixnum#*===
----
<source lang=ruby>fix * numeric #-> numeric_result</source>
----
Производит умножение: результат является одним из потомков класса [[Ruby/Справочник/Numeric|Numeric]] и зависит от величины результата.
Performs multiplication: the class of the resulting object depends on the class of <tt>numeric</tt> and on the magnitude of the result.
{{Похожие методы|Fixnum|**|+|-|/|%}}
===Fixnum#**===
----
<source lang=ruby>fix **( other)</source #-> rational или numeric
fix.rpower(other) #-> numeric или rational</source>
----
Производит возведение числа ''fix'' в степень ''other''. Возвращает [[Ruby/Справочник/Rational|рациональное число]], если результат рациональный (то есть, когда ''other'' < 0).
Alias for #rpower
<source lang=ruby>2 ** 8 #-> 256
2 ** -8 #-> Rational(1,256)</source>
{{Идентичные методы|Fixnum|**|rpower}}
{{Похожие методы|Fixnum|*|+|-|/|%|power!}}
===Fixnum#+===
----
<source lang=ruby>fix + numeric #-> numeric_result</source>
----
Производит сложение: результат является одним из потомков класса [[Ruby/Справочник/Numeric|Numeric]] и зависит от величины результата.
Performs addition: the class of the resulting object depends on the class of <tt>numeric</tt> and on the magnitude of the result.
{{Похожие методы|Fixnum|**|*|-|/|%}}
===Fixnum#-===
----
<source lang=ruby>fix - numeric #-> numeric_result</source>
----
Производит вычитание: результат является одним из потомков класса [[Ruby/Справочник/Numeric|Numeric]] и зависит от величины результата.
Performs subtraction: the class of the resulting object depends on the class of <tt>numeric</tt> and on the magnitude of the result.
{{Похожие методы|Fixnum|**|+|*|/|%}}
===Fixnum#-@===
----
<source lang=ruby>-fix #-> integer</source>
----
NegatesОтрицание <tt>fix</tt> (whichможет mightвернуть returnзначение aкласса [[Ruby/Справочник/Bignum|Bignum]]).
===Fixnum#/===
----
Строка 65 ⟶ 79 :
fix.div(numeric) #-> numeric_result</source>
----
Производит целочисленное деление: результат является одним из потомков класса [[Ruby/Справочник/Numeric|Numeric]] и зависит от величины результата.
Performs division: the class of the resulting object depends on the class of <tt>numeric</tt> and on the magnitude of the result.
{{Идентичные методы|Fixnum|/|div}}
{{Похожие методы|Fixnum|**|+|-|*|%}}
===Fixnum#<===
----
<source lang=ruby>fix < other #-> true orили false</source>
----
ReturnsВозвращает <tt>true</tt>, ifесли theзначение valueчисла of <tt>''fix</tt>'' isменьше, lessчем thanзначение thatчисла of <tt>''other</tt>''.
===Fixnum#<<===
----
<source lang=ruby>fix << count #-> integer</source>
----
Побитовый сдвиг числа ''fix'' влево на ''count'' позиций (вправо, если ''count'' меньше нуля).
Shifts <i>fix</i> left <i>count</i> positions (right if <i>count</i> is negative).
===Fixnum#<====
----
<source lang=ruby>fix <= other #-> true orили false</source>
----
Возвращает <tt>true</tt>, если значение числа ''fix'' меньше или равно значению числа ''other''.
Returns <tt>true</tt> if the value of <tt>fix</tt> is less thanor equal to that of <tt>other</tt>.
===Fixnum#<=>===
----
<source lang=ruby>fix <=> numeric #-> -1, 0, +1</source>
----
Сравнение -- возвращает -1, 0 или +1, если значение числа ''fix'' меньше, равно или больше значения числа ''numeric'', соотвественно. Это базис для тестов в примеси [[Ruby/Справочник/Comparable|Comparable]].
Comparison---Returns -1, 0, or +1 depending on whether <i>fix</i> is less than, equal to, or greater than <i>numeric</i>. This is the basis for the tests in <tt>Comparable</tt>.
===Fixnum#=====
----
<source lang=ruby>fix == other #-> true или false</source>
----
Возвращает <tt>true</tt>, если значение числа ''fix'' равно значениею числа ''other''.
Return <tt>true</tt> if <tt>fix</tt> equals <tt>other</tt> numerically.
<source lang=ruby>1 == 2 #=&gt;-> false
1 == 1.0 #-> true</source>
===Fixnum#>===
----
<source lang=ruby>fix > other #-> true orили false</source>
----
ReturnsВозвращает <tt>true</tt>, ifесли theзначение valueчисла of <tt>''fix</tt>'' isбольше, greaterчем thanзначение thatчисла of <tt>''other</tt>''.
===Fixnum#>====
----
<source lang=ruby>fix >= other #-> true orили false</source>
----
Возвращает <tt>true</tt>, если значение числа ''fix'' больше или равно, чем значение числа ''other''.
Returns <tt>true</tt> if the value of <tt>fix</tt> is greater than or equal to that of <tt>other</tt>.
===Fixnum#>>===
----
<source lang=ruby>fix >> count #-> integer</source>
----
Побитовый сдвиг числа ''fix'' вправо на ''count'' позиций (влево, если ''count'' меньше нуля).
Shifts <i>fix</i> right <i>count</i> positions (left if <i>count</i> is negative).
===Fixnum#[]===
----
<source lang=ruby>fix[n] #-> 0, 1</source>
----
Побитовый доступ -- возвращает ''n''ый бит двоичного представления числа ''fix'', где ''fix''[0] -- младший significant бит.
Bit Reference---Returns the <i>n</i>th bit in the binary representation of <i>fix</i>, where <i>fix</i>[0] is the least significant bit.
<source lang=ruby>a = 0b11001100101010
30.downto(0) do |n| print a[n] end</source>
Строка 121 ⟶ 137 :
<source lang=ruby>fix ^ other #-> integer</source>
----
Побитовое <tt>ИСКЛЮЧАЮЩЕЕ ИЛИ</tt>.
Bitwise EXCLUSIVE OR.
===Fixnum#abs===
----
<source lang=ruby>fix.abs #-> aFixnumfixnum</source>
----
Возвращает [[w:Абсолютное значение|абсолютное значение]] числа ''fix''.
Returns the absolute value of <i>fix</i>.
<source lang=ruby>-12345.abs #-> 12345
12345.abs #-> 12345</source>
Строка 134 ⟶ 150 :
fix.div(numeric) #-> numeric_result</source>
----
Производит целочисленное деление: результат является одним из потомков класса [[Ruby/Справочник/Numeric|Numeric]] и зависит от величины результата.
Performs division: the class of the resulting object depends on the class of <tt>numeric</tt> and on the magnitude of the result.
{{Идентичные методы|Fixnum|/|div}}
===Fixnum#divmod===
----
<source lang=ruby>fix.divmod(numeric) #-> array</source>
----
{{info|Полезно взглянуть в описание метода [[Ruby/Справочник/Numeric#Numeric#divmod|Numeric#divmod]] для получения более детальной информации}}
See <tt>Numeric#divmod</tt>.
===Fixnum#id2name===
----
<source lang=ruby>fix.id2name #-> string orили nil</source>
----
Возвращает имя объекта с <tt>id</tt> равным ''fix''. Возвращает <tt>nil</tt>, если в символьной таблице не найдено ни одного символа, соответствующего значению ''fix''.
Returns the name of the object whose symbol id is <i>fix</i>. If there is no symbol in the symbol table with this value, returns <tt>nil</tt>. <tt>id2name</tt> has nothing to do with the <tt>Object.id</tt> method. See also <tt>Fixnum#to_sym</tt>, <tt>String#intern</tt>, and class <tt>Symbol</tt>.
<source lang=ruby>symbol = :@inst_var #-> :@inst_var
id = symbol.to_i #-> 9818
id.id2name #-> "@inst_var"</source>
{{info|
* Для более полного представления о работе данного метода советуем взглянуть на описания методов [[Fixnum#to_sym|to_sym]], [[Ruby/Справочник/String#String#intern|String#intern]] и описание класса [[Ruby/Справочник/Symbol|Symbol]]
* Метод <tt>id2name</tt> никак не взамодействует с методом [[Ruby/Справочник/Object#Object#id|Object#id]]}}
===Fixnum#modulo===
----
Строка 153 ⟶ 173 :
fix.modulo(other) #-> Numeric</source>
----
Возвращает остаток от деления числа ''fix'' на число''other''.
Returns <tt>fix</tt> modulo <tt>other</tt>. See <tt>Numeric.divmod</tt> for more information.
{{info|Полезно взглянуть в описание метода [[Ruby/Справочник/Numeric#Numeric#divmod|Numeric#divmod]] для получения более детальной информации}}
{{Идентичные методы|Fixnum|%|modulo}}
===Fixnum#power!===
----
<source lang=ruby>fix.power!(p1 other ) #-> numeric</source>
----
Производит возведение числа ''fix'' в степень ''other''.
Alias for #**
<source lang=ruby>2.power!( 8 ) #-> 256
2.power( -8 ) #-> 0.00390625</source>
{{Похожие методы|Fixnum|**|rpower}}
===Fixnum#quo===
----
<source lang=ruby>fix.quo(numeric) #-> float</source>
fix.rdiv(numeric) #-> float</source>
----
Возвращает дробный результат деления числа ''fix'' на число ''numeric''.
Returns the floating point result of dividing <i>fix</i> by <i>numeric</i>.
<source lang=ruby>654321.quo(13731) #-> 47.6528293642124
654321.quo(13731.24) #-> 47.6519964693647</source>
{{Идентичные методы|Fixnum|quo|rdiv}}
 
(еще известен как /, rdiv)
===Fixnum#rdiv===
----
<source lang=ruby>rdivfix.quo(p1numeric)</source #-> float
fix.rdiv(numeric) #-> float</source>
----
Возвращает дробный результат деления числа ''fix'' на число ''numeric''.
Alias for #quo
<source lang=ruby>654321.rdiv(13731) #-> 47.6528293642124
654321.rdiv(13731.24) #-> 47.6519964693647</source>
{{Идентичные методы|Fixnum|quo|rdiv}}
===Fixnum#rpower===
----
<source lang=ruby>rpower(fix ** other)</source #-> rational или numeric
fix.rpower(other) #-> rational или numeric</source>
----
Производит возведение числа ''fix'' в степень ''other''. Возвращает [[Ruby/Справочник/Rational|рациональное число]], если результат рациональный (то есть, когда ''other'' < 0).
Returns a Rational number if the result is in fact rational (i.e. <tt>other</tt> &lt; 0).
<source lang=ruby>2.rpower( 8 ) #-> 256
 
2.rpower( -8 ) #-> Rational(1,256)</source>
(еще известен как **)
{{Идентичные методы|Fixnum|**|rpower}}
{{Похожие методы|Fixnum|power!}}
===Fixnum#size===
----
<source lang=ruby>fix.size #-> fixnum</source>
----
Возвращает количество байт машинного представления числа ''fix''.
Returns the number of <i>bytes</i> in the machine representation of a <tt>Fixnum</tt>.
<source lang=ruby>1.size #-> 4
-1.size #-> 4
Строка 190 ⟶ 222 :
===Fixnum#to_f===
----
<source lang=ruby>fix.to_f #-> float</source>
----
Преобразует значение числа ''fix'' к классу [[Ruby/Справочник/Float|Float]].
Converts <i>fix</i> to a <tt>Float</tt>.
{{Похожие методы|Fixnum|to_s|to_sym}}
===Fixnum#to_s===
----
<source lang=ruby>fix.to_s( base=10 ) #-> aStringstring</source>
----
Возвращает строку, где число ''fix'' имеет основание системы счисления равное ''base'' (между 2 и 36). По умолчанию ''base''=10 (то есть десятичная система счисления).
Returns a string containing the representation of <i>fix</i> radix <i>base</i> (between 2 and 36).
<source lang=ruby>12345.to_s #-> "12345"
12345.to_s(2) #-> "11000000111001"
Строка 204 ⟶ 237 :
12345.to_s(16) #-> "3039"
12345.to_s(36) #-> "9ix"</source>
{{Похожие методы|Fixnum|to_f|to_sym}}
===Fixnum#to_sym===
----
<source lang=ruby>fix.to_sym #-> aSymbolsymbol</source>
----
Возвращает [[Ruby/Справочник/Symbol|символ]], которому соотвествует значение ''fix''.
Returns the symbol whose integer value is <i>fix</i>. See also <tt>Fixnum#id2name</tt>.
<source <codelang=ruby>fred = :fred.to_i
fred.id2name #-> "fred"
fred.to_sym #-> :fred</codesource>
{{Похожие методы|Fixnum|to_s|to_f|id2name}}
===Fixnum#xchr===
----
<source lang=ruby>fix.xchr() #-> string</source>
----
XML-версия метода [[Ruby/Справочник/Integer#Integer#chr|Integer#chr]].
XML escaped version of chr
===Fixnum#zero?===
----
<source lang=ruby>fix.zero? #-> true orили false</source>
----
ReturnsВозвращает <tt>true</tt>, ifесли <i>значение ''fix</i>'' isравно zeroнулю.
===Fixnum#|===
----
<source lang=ruby>fix | other #-> integer</source>
----
Побитовое <tt>ИЛИ</tt>.
Bitwise OR.
===Fixnum#~===
----
<source lang=ruby>~fix #-> integer</source>
----
Побитовое <tt>НЕ</tt>.
One's complement: returns a number where each bit is flipped.