Ruby/Справочник/Объединение

Материал из Викиучебника — открытых книг для открытого мира

Класс Array[править]

Массив — упорядоченная коллекция произвольных объектов с целочисленной индексацией. Нумерация элементов массива начинается с 0, как в языках Си или Java. Отрицательный индекс предполагает отсчет с конца массива, то есть индексу -1 соответствует последний элемент массива, -2 — предпоследний, и так далее.


Примеси

Enumerable (all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find, find_all, grep, group_by, include?, index_by, inject, map, max, member?, min, partition, reject, select, sort, sort_by, sum, to_a, to_set, zip)

Методы класса

[], new

Методы объекта

[]=, [], &, |, *, +, -, <<, <=>, ==, abbrev, assoc, append, at, bsearch, bsearch_index, clear, collect!, collect, combination, compact!, compact, concat, count, delete_at, delete_if, delete, each_index, each, empty?, eql?, fetch, fill, first, flatten!, flatten, frozen?, hash, include?, indexes, index, indices, insert, inspect, join, last, length, map!, map, min, nitems, pack, pop, push, rassoc, reject!, reject, replace, reverse!, reverse_each, reverse, rindex, rotate, rotate!, sample, select, shift, shuffle, size, slice!, slice, sort!, sort, to_ary, to_a, to_s, transpose, uniq!, uniq, unshift, values_at, zip

Array::[][править]


Array::[](...)

Возвращает новый массив, заполненный указанными объектами.

Array.[](1, 'a', /^A/)
Array[1, 'a', /^A/]
[1, 'a', /^A/]

Array::new[править]


Array.new(array)
Array.new(size=0, obj = nil)
Array.new(size){ |index| block }

Возвращает новый массив. В первой форме вызова, создается пустой массив. Во второй, создается массив размера size, заполненный копиями obj (то есть, size ссылок на obj). В третьей, создается копия массив, переданного в качестве параметра (массив создается при помощи вызова метода to_ary от массива-параметра). В последнем случае, создается массив указанного размера. Каждый элемент в этом массиве вычисляется в указанном блоке, которому передается индекс обрабатываемого элемента. Результат блока записывается в качестве значения элемента в массив.

Array.new
Array.new(2)
Array.new(5, "A")

# только одна копия объекта создается
a = Array.new(2, Hash.new)
a[0]['cat'] = 'feline'
a
a[1]['cat'] = 'Felix'
a

# здесь создается несколько копий объекта
a = Array.new(2) { Hash.new }
a[0]['cat'] = 'feline'
a

squares = Array.new(5) { |i| i*i }
squares

copy = Array.new(squares)

Array#&[править]


array & other_array

Пересечение множеств — возвращает новый массив, состоящий из элементов, которые есть в обоих массивах, но без дубликатов.

[1, 1, 3, 5] & [1, 2, 3]  #=> [1, 3]

Array#|[править]


array | other_array  #=> an_array

Объединение множеств — возвращает новый массив, который объединяет элементы массивов array и other_array, но с удаленными дубликатами.

["a", "b", "c"] | ["c", "d", "a"]  #=> ["a", "b", "c", "d"]

Array#*[править]


array * int  #=> an_array
array * str  #=> a_string

Повторение — со строковым аргументом эквивалентен коду array.join(str). Иначе, возвращает новый массив, состоящий из int сцепленных копий array.

[1, 2, 3] * 3    #=> [1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3] * ","  #=> "1,2,3"

Array#+[править]


array + other_array  #=> an_array

Сцепление — возвращает новый массив, созданный из двух массивов путем добавления одного к другому.

[1, 2, 3] + [4, 5]  #=> [1, 2, 3, 4, 5]

Array#-[править]


array - other_array  #=> an_array

Вычитание массивов — возвращает новый массив, который копирует оригинальный массив, но удаляет из него элементы, которые есть в другом массиве.

[1, 1, 2, 2, 3, 3, 4, 5] - [1, 2, 4]  #=> [3, 3, 5]
Информация

Если вам необходима разность множеств, а не вычитание массивов, то смотрите в сторону класса Set

Array#<<[править]


array << obj  #=> array

Добавить элемент — добавляет передаваемый объект в конец массива. Возвращает массив с уже добавленным элементом.

[1, 2] << "c" << "d" << [3, 4]  #=> [1, 2, "c", "d", [3, 4]]
Информация

Метод push имеет примерно такую же функциональность

Array#<=>[править]


array <=> other_array  #=> -1, 0, +1

Сравнение — возвращает целое число (-1, 0, или +1) если текущий массив меньше, равен или больше другого массива. Соответствующие элементы обоих массивов сравниваются (используется метод<=>). Если какая либо из пар элементов не совпадает, то возвращается результат этого сравнения. Если все пары элементов совпадают, то возвращается результат сравнения по длине. Таким образом, два массива считаются «равными» (по мнению методаArray#<=>) тогда и только тогда, когда их длины и соответствующие пары элементов совпадают.

["a", "a", "c"] <=> ["a", "b", "c"]  #=> -1
[1, 2, 3, 4, 5] <=> [1, 2, 3, 4, 5]  #=>  0
[1, 2, 3, 4, 5] <=> [1, 2, 3, 4]     #=> +1

Array#==[править]


array == other_array  #=> bool

Равенство — два массива считаются равными, если количество элементов и соответствующие пары элементов равны (используется метод==).

["a", "b"]    == ["a", "b", 5]    #=> false
["a", "b", 5] == ["a", "b", 5]    #=> true
["a", "b", 5] == ["a", "b", "c"]  #=> false

Array#[][править]


array[index]                #=> obj      или nil
array[start, length]        #=> an_array или nil
array[range]                #=> an_array или nil
array.slice(index)          #=> obj      или nil
array.slice(start, length)  #=> an_array или nil
array.slice(range)          #=> an_array или nil

Получение значения элемента — возвращает элемент с индексом index, или подмассив длины length, начиная с индекса start, или подмассив, который располагается в диапазоне range. Отрицательная индексация предполагает отчет с конца массива (по индексу -1 располагается последний элемент). Возвращаетnil, если индекс выходит за диапазон допустимых значений.

a = ["a", "b", "c", "d", "e"]
a[2] + a[0] + a[1]     #=> "cab"
a[6]                   #=> nil
a[1, 2]                #=> ["b", "c"]
a[1..3]                #=> ["b", "c", "d"]
a[4..7]                #=> ["e"]
a[6..10]               #=> nil
a[-3, 3]               #=> ["c", "d", "e"]
# Специальные случаи:
a[5]                   #=> nil
a[5, 1]                #=> []
a[5..10]               #=> []
Информация
  • Методы slice и [] — одно и тоже!
  • Существует метод at, который обладает схожей, но меньшей функциональностью

Array#[]=[править]


array[index] = obj  #=> obj
array[start, length] = obj или an_array или nil  #=> obj или an_array или nil
array[range]         = obj или an_array или nil  #=> obj или an_array или nil

Распределение элементов — помещает элемент в array поindex, или заменяет подмассив некоторойlength (длины), начиная с индексаstart, или заменяет подмассив в определенномrange (диапазоне). Если индексация превышает текущий размер массива, то массив увеличивается автоматически. Отрицательная индексация подразумевает отсчет с конца массива. Если для второго случая использоватьlength равную 0, то указанные элементы будут вставлены перед элементом с индексомindex. Если все параметры для второго и третьего случая задать равнымиnil, то изarray будут удалены все элементы. Ошибка IndexError появляется тогда, когда отрицательный индекс указывает на элемент, расположенный перед началом массива.

a = Array.new
a[4] = "4"                 #=> [nil, nil, nil, nil, "4"]
a[0, 3] = ['a', 'b', 'c']  #=> ["a", "b", "c", nil, "4"]
a[1..2] = [1, 2]           #=> ["a", 1, 2, nil, "4"]
a[0, 2] = "?"              #=> ["?", 2, nil, "4"]
a[0..2] = "A"              #=> ["A", "4"]
a[-1]   = "Z"              #=> ["A", "Z"]
a[1..-1] = nil             #=> ["A"]
Информация

Полезно знать, что добавления элементов в массив существуют еще методы push и unshift

Array#abbrev[править]


array.abbrev(pattern = nil)

Вычисляет набор однозначных сокращений для строк в array. Если в качестве pattern передается правило или строка, то будут обрабатываться только строки, которые соответствуют правилу или начинаются с данной строки.

%w{ car cone }.abbrev  #=> { "ca" => "car", "car"  => "car",
                       #=>   "co" => "cone", "con" => "cone",
                       #=> "cone" => "cone" }

Array#assoc[править]


array.assoc(obj)  #=> an_array или nil

Ищет в двумерном массиве массив, первый элемент которого равен obj (для сравнения используется метод==). Возвращает первый найденный массив (то есть, ассоциированный массив) или nil, если таковой найти не удалось.

s1 = ["colors", "red", "blue", "green"]
s2 = ["letters", "a", "b", "c"]
s3 = "foo"
a  = [s1, s2, s3]
a.assoc("letters")  #=> ["letters", "a", "b", "c"]
a.assoc("foo")      #=> nil
Информация

Для понимания происходящего, полезно взглянуть на метод rassoc

Array#append[править]


array.append(*args)  #=> array

Добавить элемент — добавляет передаваемый объект (или несколько объектов) в конец массива. Возвращает массив с выполненным преобразованием.

a = ["a", "b", "c"]
a.push("d", "e", "f")  #=> ["a", "b", "c", "d", "e", "f"]
a                      #=> ["a", "b", "c", "d", "e", "f"]

Добавляет каждый аргумент как один элемент, даже если это другой массив:

a = [:jay, "shri", 108]
a1 = a.push([:om, :tat], [:sat, :rama])
a1 # => [:jay, "shri", 108, [:om, :tat], [:sat, :rama]]
Информация
  • Методы append и push — одно и то же!
  • Данный метод обычно используют совместно с методами shift, pop и unshift

Array#at[править]


array.at(index)  #=> obj или nil

Возвращает элемент массива array с индексом index. Отрицательная индексация подразумевает отсчет с конца массива. возвращаетnil, если индекс выходит за пределы допустимого диапазона.

a = ["a", "b", "c", "d", "e"]
a.at(0)   #=> "a"
a.at(-1)  #=> "e"
Информация
  • Рекомендуется также взглянуть на метод [] (aka «батарейка»), который обладает схожим функционалом
  • Методat работает чуть быстрей метода[] за счет того, что не обрабатывает ничего кроме целочисленных индексов, то есть за счет игнорирования диапазонов

Array#bsearch[править]


array.bsearch{|element| ... } #=> obj
array.bsearch                 #=> an_enumerator

Возвращает элемент из self, выбранного бинарным поиском. self следует отсортировать, но это не проверяется.

Используя двоичный поиск, находит значение из этого array, которое удовлетворяет заданному условию в O (log n), где n - размер массива.

Есть два режима поиска:

Режим поиска-минимум: блок должен возвращать true или false.

Режим любого поиска: блок должен возвращать числовое значение.

Блок не должен смешивать режимы, иногда возвращая true или false, а иногда и возвращая числовое значение, но это не проверяется.

Режим поиска минимума

В режиме минимального поиска блок всегда возвращает true или false. Дальнейшее требование (хотя и не проверяемое) состоит в том, что не существует таких индексов i и j, что:

0 <= i < j <= self.size

Блок возвращает true для self[i] и false для self[j]

В режиме минимального поиска метод bsearch возвращает первый элемент, для которого блок возвращает true.

Примеры:
a = [0, 4, 7, 10, 12]
a.bsearch {|x| x >= 4 } # => 4
a.bsearch {|x| x >= 6 } # => 7
a.bsearch {|x| x >= -1 } # => 0
a.bsearch {|x| x >= 100 } # => nil

Продолжение следует... https://ruby-doc.org/core-3.0.2/Array.html

Информация

Рекомендуется также взглянуть на метод bsearch_index, который обладает схожим функционалом

Array#bsearch_index[править]


array.bsearch_index{|element| ... } #=> int или nil
bsearch_index                       #=> an_enumerator

Ищет себя, как описано в методе bsearch, но возвращает индекс найденного элемента вместо самого элемента.

Информация

Рекомендуется также взглянуть на метод bsearch, который обладает схожим функционалом

Array#clear[править]


array.clear  #=> array

Удаляет все элементы из массива array.

a = ["a", "b", "c", "d", "e"]
a.clear  #=> [ ]

Array#collect[править]


array.collect{ |item| block }  #=> an_array
array.map{ |item| block }      #=> an_array

Выполняет выражение block для каждого элемента массива array. Создает новый массив, который состоит из значений, которые получены при вычислении выражения block.

a = ["a", "b", "c", "d"]
a.collect { |x| x + "!" }  #=> ["a!", "b!", "c!", "d!"]
a                          #=> ["a", "b", "c", "d"]
Информация

Array#collect![править]


array.collect!{ |item| block }  #=> array
array.map!{ |item| block }      #=> array

Выполняет выражение block для каждого элемента массива array, вычисленное выражение подставляется вместо текущего элемента.

a = ["a", "b", "c", "d"]
a.collect!{ |x| x + "!" }
a  #=> ["a!", "b!", "c!", "d!"]
Информация


Array#combination[править]


array.combination(n) {|element| ... } #=> self
combination(n)                        #=> new_enumerator

Вызывает block, если он задан, с комбинациями элементов self; возвращает self. Порядок комбинаций не определен.

Когда заданы block и входящий в диапазон положительный целочисленный аргумент n (0 <n <= self.size), вызывает block со всеми комбинациями кортежей из n элементов self.

Пример:

a = [0, 1, 2]
a.combination(2) {|combination| p combination }
#=>
[0, 1]
[0, 2]
[1, 2]
a #=> [0, 1, 2]

Другие примеры:

a = [0, 1, 2]
a.combination(3) {|combination| p combination }
Output:

[0, 1, 2]
When n is zero, calls the block once with a new empty Array:

a = [0, 1, 2]
a1 = a.combination(0) {|combination| p combination }
Output:

[]
When n is out of range (negative or larger than self.size), does not call the block:

a = [0, 1, 2]
a.combination(-1) {|combination| fail 'Cannot happen' }
a.combination(4) {|combination| fail 'Cannot happen' }
Returns a new Enumerator if no block given:

a = [0, 1, 2]
a.combination(2) # => #<Enumerator: [0, 1, 2]:combination(2)>

Array#compact[править]


array.compact  #=> an_array

Возвращает копию массива array из которого удалены все элементы nil.

["a", nil, "b", nil, "c", nil].compact  #=> ["a", "b", "c"]

Array#compact![править]


array.compact!  #=> array или nil

Удаляет все элементы nil из массива array. Возвращает nil, если изменять ничего не потребовалось.

["a", nil, "b", nil, "c"].compact!  #=> ["a", "b", "c"]
["a", "b", "c"].compact!            #=> nil

Array#concat[править]


array.concat(other_array)  #=> array

Добавляет к массиву array элементы массива other_array.

["a", "b"].concat(["c", "d"]) #=> ["a", "b", "c", "d"]

Array#count[править]


array.count                  #=> int
array.count(obj)             #=> int
array.count { |item| block } #=> int

Без аргументов возвращает количество элементов массива. Если задан аргумент, считает количество элементов которые равны obj через ==. Если передан блок, считает количество элементов для которых блок возвращает true.

ary = [1, 2, 4, 2]
ary.count                  #=> 4
ary.count(2)               #=> 2
ary.count { |x| x%2 == 0 } #=> 3

Array#delete[править]


array.delete(obj)           #=> obj или nil 
array.delete(obj){ block }  #=> obj или nil

Удаляет все элементы массива array, которые равны obj. Если ничего не было удалено, то возвращаетnil. Если задан блок, то, в случае отсутствия элементов для удаления, возвращает результат блока.

a = ["a", "b", "b", "b", "c"]
a.delete("b")                  #=> "b"
a                              #=> ["a", "c"]
a.delete("z")                  #=> nil
a.delete("z") { "not found" }  #=> "not found"

Array#delete_at[править]


array.delete_at(index)  #=> obj или nil

Удаляет элемент из массива array, который имеет индекс index. Возвращает значение удаленного элемента илиnil, если index находится вне допустимого диапазона.

a = %w(ant bat cat dog)
a.delete_at(2)   #=> "cat"
a                #=> ["ant", "bat", "dog"]
a.delete_at(99)  #=> nil
Информация

Метод slice! имеет схожую функциональность

Array#delete_if[править]


array.delete_if {|item| block }  #=> array

Удаляет все элементы массива array для которых значение внутри блока block равно true.

a = ["a", "b", "c"]
a.delete_if {|x| x >= "b" }  #=> ["a"]
a                            #=> ["a"]
Информация

Полезно посмотреть на следующие итераторы reject и reject!, которые имеют схожую функциональность

Array#each[править]


array.each {|item| block }  #=> array

Выполняет код в block для каждого элемента массива array, передавая в блок текущий элемент в качестве параметра.

a = ["a", "b", "c"]
a.each { |x| print x, " -- " }

результат:

a -- b -- c --
Информация
  • Данный итератор возвращает в качестве результата исходный массив. Это следует учитывать при построении цепочки методов
  • Следует использовать данный метод только тогда, когда задачу невозможно решить при помощи других итераторов

Array#each_index[править]


array.each_index { |index| block }  #=> array

Работает точно также, как и each, но передает в блок не текущий элемент, а индекс текущего элемента.

a = ["a", "b", "c"]
a.each_index { |x| print x, " -- " }

результат:

0 -- 1 -- 2 --

Array#empty?[править]


array.empty?  #=> true или false

Возвращаетtrue, если array не содержит элементов.

[].empty?  #=> true

Array#eql?[править]


array.eql?(other)  #=> true или false

Возвращаетtrue, если array и other являются одним и тем же объектом или оба массива обладают одинаковым содержимым

Array#fetch[править]


array.fetch(index)                    #=> obj
array.fetch(index, default )          #=> obj
array.fetch(index) { |index| block }  #=> obj

Попытка получить элемент массива array по индексу index. Если индекс выходит за пределы массива то, в первой форме вызова возникнет ошибка IndexError, чтобы это предотвратить используется вторая форма вызова, которой будет возвращено значение default, так же для предотвращения ошибки IndexError используется третья форма вызова, которой будет возвращено значение блока block (в который передается запрашиваемый индекс в качестве параметра). Если во второй и третьей форме вызова будет использован индекс существующего элемента, то fetch просто вернет значение этого элемента. Отрицательная индексация подразумевает отсчёт с конца массива.

a = [11, 22, 33, 44]
a.fetch(1)              #=> 22
a.fetch(-1)             #=> 44
a.fetch(4, 'cat')       #=> "cat"
a.fetch(4) { |i| i*i }  #=> 16

Array#fill[править]


array.fill(obj)                                #=> array
array.fill(obj, start [, length])              #=> array
array.fill(obj, range )                        #=> array
array.fill {|index| block }                    #=> array
array.fill(start [, length]) {|index| block }  #=> array
array.fill(range) { |index| block }            #=> array

Первые три формы вызова заменяют указанные элементы массива array на значение obj. Если значение start равно nil, то это эквивалентно

start = 0

Если значение length равноnil, то это эквивалентно

length = array.[[#Array#length|length]]

Последние три формы вызова заполняют массив значением выражения в блоке block (в который передается индекс текущего заменяемого элемента).

a = ["a", "b", "c", "d"]
a.fill("x")             #=> ["x", "x", "x", "x"]
a.fill("z", 2, 2)       #=> ["x", "x", "z", "z"]
a.fill("y", 0..1)       #=> ["y", "y", "z", "z"]
a.fill {|i| i*i}        #=> [0, 1, 4, 9]
a.fill(-2) {|i| i*i*i}  #=> [0, 1, 8, 27]

Array#first[править]


array.first     #=> obj или nil
array.first(n)  #=> an_array

Возвращает первый элемент или первыеn элементов массива array. Если массив пуст, то для первой формы вызова (безn) возвращаетсяnil, а для второй — пустой массив.

a = ["q", "r", "s", "t"]
a.first     #=> "q"
a.first(1)  #=> ["q"]
a.first(3)  #=> ["q", "r", "s"]

Array#flatten[править]


array.flatten #=> an_array

Преобразует многомерный массив array в одномерный.

s = [1, 2, 3]          #=> [1, 2, 3]
t = [4, 5, 6, [7, 8]]  #=> [4, 5, 6, [7, 8]]
a = [s, t, 9, 10]      #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten              #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Array#flatten![править]


array.flatten! #=> array или nil

Преобразует многомерный массив array в одномерный. Возвращаетnil, если массив array изначально был одномерным.

a = [1, 2, [3, [4, 5]]]
a.flatten!  #=> [1, 2, 3, 4, 5]
a.flatten!  #=> nil
a           #=> [1, 2, 3, 4, 5]

Array#frozen?[править]


array.frozen?  #=> true или false

Возвращаетtrue, если массив array заморожен (или временно заморожен, пока идет сортировка).

Array#hash[править]


array.hash  #=> fixnum

Вычисляет хеш-код для массива array. Два массива с одним и тем же содержимым будут иметь одинаковый хеш-код (именно его использует eql?).

Array#include?[править]


array.include?(obj)  #=> true или false

Возвращаетtrue, если объект obj является элементом массива array (то есть какой-то из элементов массива== obj). Иначе —false.

a = ["a", "b", "c"]
a.include?("b")  #=> true
a.include?("z")  #=> false

Array#index[править]


array.index(obj)  #=>  int или nil

Возвращает индекс первого вхождения элемента в массив array, который== obj. Возвращаетnil, если такой элемент не был найден.

a = ["a", "b", "c"]
a.index("b")  #=> 1
a.index("z")  #=> nil
Информация

Существует так же метод rindex, который возвращает первый соответствующий элемент с конца массива.

Array#indexes[править]


array.indexes(i1, i2, ... iN)   #=> an_array
array.indices(i1, i2, ... iN )  #=> an_array

Array#indices[править]


array.indexes(i1, i2, ... iN)  #=> an_array
array.indices(i1, i2, ... iN)  #=> an_array

Array#insert[править]


array.insert(index, obj...)  #=> array

Вставляет полученные значения перед элементом индексом index (может быть отрицательным).

a = %w{ a b c d }
a.insert(2, 99)        #=> ["a", "b", 99, "c", "d"]
a.insert(-2, 1, 2, 3)  #=> ["a", "b", 99, "c", 1, 2, 3, "d"]

Array#inspect[править]


array.inspect  #=> string

Создает «печатную» версию массива array.

 a = [ad, cc, xczxc, 1, 1..4]
 a.inspect	=> 	[\ad\, \cc\, \xczxc\, 1, 1..4]

Array#join[править]


array.join(sep=$,)  #=> str

Возвращает строку, созданную путем преобразования каждого элемента массива в строку, разделенных строкой sep.

["a", "b", "c" ].join       #=> "abc"
["a", "b", "c" ].join("-")  #=> "a-b-c"

Array#last[править]


array.last     #=> obj или nil
array.last(n)  #=> an_array

Возвращает последний элемент или последниеn элементов массива array. Если массив пуст, то для первой формы вызова (безn) возвращаетсяnil, а для второй — пустой массив.

[ "w", "x", "y", "z" ].last  #=> "z"

Array#length[править]


array.length  #=> int
array.size    #=> int

Возвращает количество элементов в array. Может быть нулевым (для пустого массива).

[ 1, 2, 3, 4, 5 ].length  #=> 5
Информация

Методы length и size — одно и то же!

Array#map[править]


array.collect {|item| block }  #=> an_array
array.map {|item| block }      #=> an_array

Перебирает массив и составляет новый массив из элементов, где каждый элемент - это "обработанный" элемент исходного массива. Исходный массив при этом не изменяется.

a = ["a", "b", "c", "d"]
a.map { |x| x + "!" }  #=> ["a!", "b!", "c!", "d!"]
a                      #=> ["a", "b", "c", "d"]
a = [1, 2, 3, 4]
a.map { |x| x * x }  #=> [1, 4, 9, 16]
a                      #=> [1, 2, 3, 4]
Информация

Array#map![править]


array.collect! { |item| block }  #=> array
array.map! { |item| block }      #=> array

Выполняет выражение block для каждого элемента массива array, вычисленное выражение подставляется вместо текущего элемента. Метод map! перезапишет текущий массив в своей переменной.

a = ["a", "b", "c", "d"]
a.map! {|x| x + "!" } #=> ["a!", "b!", "c!", "d!"]
a  #=>  ["a!", "b!", "c!", "d!"]
Информация

Array#min[править]


array.min  #=> obj

Возвращает объект в ary с минимальным значением. Первая форма предполагает, что все объекты реализуют Comparable; вторая использует блок для возврата <=> b.

Array#nitems[править]


array.nitems  #=> int

Возвращает количество элементов массива array, значение которых не равноnil. Может быть нулевым (для пустого массива или массива, который заполненnil.

[ 1, nil, 3, nil, 5 ].nitems  #=> 3

Array#pack[править]


array.pack(aTemplateString)  #=> aBinaryString

Упаковывает содержимое массива array в двоичную последовательность (в виде строки) в соответствии с опциями в строке aTemplateString (см. таблицу ниже). После опцийA, a, иZ может идти число, которое указывает на ширину результирующего поля. Для остальных, число после опций означает — количество элементов массива которые необходимо обработать в соответствии с указанной опцией. Если в вместо числа после директивы стоит символ* («звездочка»), то все оставшиеся элементы массива необходимо обработать в соответствии с этой опцией. Любую из опцийs, S, i, I, l и L можно завершать_ (знаком подчеркивания) для того, чтобы использовать размер для базовой платформы; иначе, будет использован платформонезависимый размер. В строке aTemplateString пробелы игнорируются.

a = ["a", "b", "c"]
n = [ 65, 66, 67 ]
a.pack("A3A3A3")  #=> "a  b  c  "
a.pack("a3a3a3")  #=> "a\000\000b\000\000c\000\000"
n.pack("ccc")     #=> "ABC"

Опции методаpack.

Опция Описание
@
Переместиться на абсолютную позицию
A
Строка ASCII (дополненная пробелами до указанной ширины)
a
Строка ASCII (дополненная нулевыми символами до указанной ширины)
B
Двоичная строка (возрастающая двоичная последовательность)
b
Двоичная строка (убывающая двоичная последовательность)
C
Беззнаковый 8-битный символ (char)
c
8-битный символ (char)
D, d
Число с плавающей точкой двойной точности, собственный формат («нативный»)
E
Число с плавающей точкой двойной точности, прямой порядок двоичной последовательности
e
Число с плавающей точкой одинарной точности, прямой порядок двоичной последовательности
F, f
Число с плавающей точкой одинарной точности, собственный формат («нативный»)
G
Число с плавающей точкой двойной точности, «сетевая» (обратная) двоичная последовательность
g
Число с плавающей точкой одинарной точности, «сетевая» (обратная) двоичная последовательность
H
Двоичная строка (верхний полубайт идет первым)
h
Двоичная строка (нижний полубайт идет первым)
I
Беззнаковое целое (unsigned integer)
i
Целое (integer)
L
Большое беззнаковое целое (usigned long)
l
Большое целое (long)
M
Строка готовая к печати, закодированная MIME (см. RFC2045)
m
Строка закодированная Base64 (см. RFC4648)
N
Большое целое (long),«сетевая» (обратная) двоичная последовательность
n
Короткое целое (short), «сетевая» (обратная) двоичная последовательность
P
Указатель на структуру (строка фиксированной длины)
p
Указатель на строку (с завершающим нулевым символом)
Q, q
64-битное число
S
Беззнаковое короткое целое (unsigned short)
s
Короткое целое (short)
U
UTF-8
u
Строка UU-кодированная
V
Длинное целое (long), прямой порядок байт
v
Короткое целое (short), прямой порядок байт
w
BER-упакованное целое
X
Символ возврата коретки
x
Нулевой символ
Z
Тоже самое, что и директиваa, исключая то, что нулевой символ добавляется со* («звездочкой»)
Информация

Данный метод обычно используется совместно с методом String#unpack, который выполняет обратные действия

Array#pop[править]


array.pop  #=> obj или nil

Удаляет последний элемент из массива

array

и возвращает его. Если на момент вызова массив был пуст, то возвращаетnil.

a = ["a", "b", "c"]
a.pop  #=> "c"
a      #=> ["a", "b"]

Array#push[править]


array.push(obj, ... )  #=> array

Добавить элемент — добавляет передаваемый объект (или несколько объектов) в конец массива. Возвращает массив с выполненным преобразованием.

a = ["a", "b", "c"]
a.push("d", "e", "f")  #=> ["a", "b", "c", "d", "e", "f"]
a                      #=> ["a", "b", "c", "d", "e", "f"]

Добавляет каждый аргумент как один элемент, даже если это другой массив:

a = [:jay, "shri", 108]
a1 = a.push([:om, :tat], [:sat, :rama])
a1 # => [:jay, "shri", 108, [:om, :tat], [:sat, :rama]]
Информация
  • Методы append и push — одно и то же!
  • Данный метод обычно используют совместно с методами shift, pop и unshift

Array#rassoc[править]


array.rassoc(key) #=> an_array или nil

Ищет в двумерном массиве массив, второй элемент которого равен key (для сравнения используется метод==). Возвращает первый найденный массив (то есть, ассоциированный массив) или nil, если таковой найти не удалось

a = [[1, "one"], [2, "two"], [3, "three"], ["ii", "two"]]
a.rassoc("two")   #=> [2, "two"]
a.rassoc("four")  #=> nil
Информация

Так же существует метод assoc, который имеет схожий функционал

Array#reject[править]


array.reject { |item| block }  #=> an_array

Метод возвращает новый массив , содержащий элементы , которые не соответствуют условию. Вы можете думать об этом как о фильтре, который удаляет ненужные элементы. Вот пример, который отклоняет все записи, содержащие буквы a:).

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
results = sharks.reject {|item| item.include?("a")}
print results                          #=> ["Tiger"]
Информация
  • Полезно взглянуть на итераторы delete_if и reject!, которые отличается лишь тем, что изменяют исходный массив
  • Данный метод реализован на базе метода Enumerable#reject

Array#reject![править]


array.reject! {|item| block }  #=> array или nil

Подобно итератору delete_if удаляет из массива array элементы, для которых значение внутри блока block равно true, но возвращает nil, если изменений в массиве сделано не было.

a = [1, 2, 3, 4, 5]
a.reject!{ |item| item > 2 }  #=> [1, 2]
a                             #=> [1, 2]
a.reject!{ |item| item > 2 }  #=> nil
Информация

Полезно посмотреть описание итератора delete_if, который делает примерно тоже самое, но название которого лучше запоминается

Array#replace[править]


array.replace(other_array) #=> self

Заменяет содержимое массива array содержимым массива other_array.

a = ["a", "b", "c", "d", "e"]
a.replace(["x", "y", "z"])  #=> ["x", "y", "z"]
a                           #=> ["x", "y", "z"]
Информация

Данный метод работает как присваивание, но может быть использован при построении цепочки методов (которую присваивание обычно разрывает). Также незаменим при необходимости изменения содержимого массива, передающегося в функцию или блок как аргумент:

def set_123(a)
  a.replace([1, 2, 3])
end

При обычном присваивании изменилась бы только ссылка a, а в вызывающем функцию коде массив остался бы неизменным.

Array#reverse[править]


array.reverse  #=> an_array

Возвращает новый массив, в котором элементы массива array стоят в обратном порядке.

["a", "b", "c"].reverse  #=> ["c", "b", "a"]
[1].reverse              #=> [1]

Array#reverse![править]


array.reverse!  #=> array

Изменяет порядок элементов в массиве array на обратный.

a = ["a", "b", "c"]
a.reverse!  #=> ["c", "b", "a"]
a           #=> ["c", "b", "a"]

Array#reverse_each[править]


array.reverse_each {|item| block }

Работает точно также, как и итератор each, но элементы массива array обрабатываются в обратном порядке.

a = ["a", "b", "c"]
a.reverse_each { |x| print x, " " }

результат:

c b a
Информация

Достичь точно такого же результата можно вот так: array.reverse.each { |item| block }

Array#rindex[править]


array.rindex(obj) #=> int или nil

Возвращает индекс последнего вхождения элемента в массив array, который== obj. Возвращаетnil, если такой элемент не был найден Простым языком - находит obj с конца.

a = ["a", "b", "b", "b", "c"]
a.rindex("b")  #=> 3
a.rindex("z")  #=> nil
Информация

Советуем взглянуть на метод index, который не только похож по названию, но, в некоторых случаях, работает точно также, как иrindex

Array#rotate[править]


array.rotate #=> an_array
array.rotate(count) #=> an_array

Возвращает новый массив, сформированный из себя(self) с элементами, повернутыми от одного конца к другому. Если аргумент не указан, возвращает новый массив, который похож на self, за исключением того, что первый элемент был повернут в последнюю позицию.

a = [:foo, 'bar', 2, 'bar']
a1 = a.rotate
a1 # => ["bar", 2, "bar", :foo]

Когда задано неотрицательное целое число счетчик(count), возвращает новый массив с элементами count, повернутыми от начала до конца:

a = [:foo, 'bar', 2]
a1 = a.rotate(2)
a1 # => [2, :foo, "bar"]

Если count большое, в качестве счетчика используется count% array.size:

a = [:foo, 'bar', 2]
a1 = a.rotate(20)
a1 # => [2, :foo, "bar"]

Если count равно нулю, возвращает копию self без изменений:

a = [:foo, 'bar', 2]
a1 = a.rotate(0)
a1 # => [:foo, "bar", 2]

Когда задано отрицательное целое число, вращается в противоположном направлении, от конца к началу:

a = [:foo, 'bar', 2]
a1 = a.rotate(-2)
a1 # => ["bar", 2, :foo]

Если count мало (далеко от нуля), в качестве count используется count% array.size:

a = [:foo, 'bar', 2]
a1 = a.rotate(-5)
a1 # => ["bar", 2, :foo]
Информация

Полезно взглянуть на rotate!, которые отличается лишь тем, что изменяют исходный массив

Array#rotate![править]


array.rotate! #=> array
array.rotate!(count) #=> array

Поворачивает себя(self) на месте, перемещая элементы с одного конца на другой; возвращает self. Если аргумент не указан, поворачивает первый элемент в последнюю позицию:

a = [:foo, 'bar', 2, 'bar']
a.rotate! # => ["bar", 2, "bar", :foo]

Когда задано неотрицательное целое число счетчик(count), вращает элементы count от начала до конца:

a = [:foo, 'bar', 2]
a.rotate!(2)
a # => [2, :foo, "bar"]

Если count большое, в качестве count используется count% array.size:

a = [:foo, 'bar', 2]
a.rotate!(20)
a # => [2, :foo, "bar"]

Если count равен нулю, возвращается без изменений:

a = [:foo, 'bar', 2]
a.rotate!(0)
a # => [:foo, "bar", 2]

Когда задано отрицательное целое число, вращается в противоположном направлении, от конца к началу:

a = [:foo, 'bar', 2]
a.rotate!(-2)
a # => ["bar", 2, :foo]

Если count мало (далеко от нуля), в качестве count используется count% array.size:

a = [:foo, 'bar', 2]
a.rotate!(-5)
a # => ["bar", 2, :foo]

Array#sample[править]


array.sample  #=> obj or nil
array.sample(n) #=> an_array
array.sample(random: rng) #=> obj
array.sample(n, random: rng) #=> an_array

Выбирает случайный элемент или n случайных элементов из массива. Элементы выбираются с использованием случайных и уникальных индексов в массиве, чтобы гарантировать, что элемент не повторяется, если массив уже содержит повторяющиеся элементы. Если массив пуст, первая форма возвращает ноль, а вторая форма возвращает пустой массив.

arr = [1, 2, 3, "R", "A", "M", "A"]
arr.sample  #=> R
arr.sample(4)  #=> ["R", 2, 1, "A"]
arr.sample(4)  #=> [2, 3, "M", 1]

Необязательный аргумент rng будет использоваться в качестве генератора случайных чисел.

arr.sample(random: Random.new(1))     #=> 3
arr.sample(4, random: Random.new(1))  #=> [3, 1, "A", "A"]

Array#select[править]


array.select {|item| block } #=> an_array

Выполняет выражение в block для каждого элемента массива array и возвращает массив, который состоит из элементов, для которых выражение в block принимает значение true.

a = %w{ a b c d e f }
a.select {|v| v =~ /[aeiou]/}  #=> ["a", "e"]
a = %w{ 1 2 3 }
a.select { |el| el.even? } #=> [2]

Перебирает массив и составляет новый массив из тех элементов, для которых условие, описанное в блоке выполнится как true [1, 2, 3].select { |el| el.even? } вернёт результат [2].

Информация

Есть итераторы Enumerable#select и #Enumerable#find_all, которые имеют схожую функциональность

Array#shift[править]


array.shift  #=> obj или nil

Удаляет первый элемент из массива array и возвращает его (как бы «сдвигает» массив влево на один элемент). Если на момент вызова массив был пуст, то возвращаетnil.

args = ["-m", "-q", "filename"]
args.shift  #=> "-m"
args        #=> ["-q", "filename"]
Информация

Данный метод обычно используют совместно с методами push, pop и unshift

Array#shuffle[править]


array.shuffle  #=> an_array
array.shuffle(random: rng) #=> an_array

Перемешивает элементы массива в случайном порядке.

arr = ["R", "A", "M", "A"]
arr.shuffle  #=> ["A", "A", "R", "M"]
arr #=> ["R", "A", "M", "A"]

Необязательный аргумент rng будет использоваться в качестве генератора случайных чисел.

arr.shuffle(random: Random.new(1))  #=> ["R", "A", "M", "A"]

Array#size[править]


array.length  #=> int
array.size    #=> int

Возвращает количество элементов в array. Может быть нулевым (для пустого массива).

[1, 2, 3, 4, 5].size   #=> 5
Информация

Методы length и size — одно и то же!

Array#slice[править]


array[index]                #=> obj      or nil
array[start, length]        #=> an_array or nil
array[range]                #=> an_array or nil
array.slice(index)          #=> obj      or nil
array.slice(start, length)  #=> an_array or nil
array.slice(range)          #=> an_array or nil

Получение значения элемента — возвращает элемент с индексом index, или подмассив длины length, начиная с индекса start, или подмассив, который располагается в диапазоне range. Отрицательная индексация предполагает отчет с конца массива (по индексу -1 располагается последний элемент). Возвращаетnil, если индекс выходит за диапазон допустимых значений.

a = ["a", "b", "c", "d", "e"]
a.slice(2) +  a.slice(0) + a.slice[1]  #=> "cab"
a.slice[6]                             #=> nil
a.slice(1, 2)                          #=> ["b", "c"]
a.slice(1..3)                          #=> ["b", "c", "d"]
a.slice(4..7)                          #=> ["e"]
a.slice(6..10)                         #=> nil
a.slice(-3, 3)                         #=> ["c", "d", "e"]
# Специальные случаи:
a.slice(5)                             #=> nil
a.slice(5, 1)                          #=> []
a.slice(5..10)                         #=> []
Информация
  • Методы slice и [] — одно и тоже!
  • Существует метод at, который обладает схожей, но меньшей функциональностью

Array#slice![править]


array.slice!(index)         #=> obj или nil
array.slice!(start, length) #=> sub_array или nil
array.slice!(range)         #=> sub_array или nil

Удаляет элемент или элементы массива array по индексу (иногда с продолжительностью length) или диапазону. Возвращает удаляемые объект, подмассив илиnil (если указанный индекс выходит за предел допустимых значений).

def slice!(*args)
  result = self[*args]
  self[*args] = nil
  result
end

a = ["a", "b", "c"]
a.slice!(1)    #=> "b"
a              #=> ["a", "c"]
a.slice!(-1)   #=> "c"
a              #=> ["a"]
a.slice!(100)  #=> nil
a              #=> ["a"]
Информация

Частными реализациями данного метода являются методы pop (array.slice!(-1) ) и shift (array.slice!(0) )

Array#sort[править]


array.sort  #=> an_array 
array.sort { |a, b| block }  #=> an_array

Возвращает новый массив, который получен путем сортировки массива array (по возрастанию). Элементы массива должны допускать сравнение при помощи метода <=>, если это не обеспечивается, то можно использовать необязательный блок. Блок предназначенный для сравнения параметров a и b, должен возвращать значения -1, 0, или +1.

a = ["d", "a", "e", "c", "b"]
a.sort                   #=> ["a", "b", "c", "d", "e"]
a.sort {|x, y| y <=> x }  #=> ["e", "d", "c", "b", "a"]
Информация

Более интересная и чаще используемая форма сортировки производится при помощи итератора Enumerable#sort_by

Array#sort![править]


array.sort!                   #=> array
array.sort! { |a, b| block }  #=> array

Сортирует массив array (по возрастанию). Элементы массива должны допускать сравнение при помощи метода <=>, если это не обеспечивается, то можно использовать необязательный блок. Блок предназначенный для сравнения параметров a и b, должен возвращать значения -1, 0, или +1.

a = ["d", "a", "e", "c", "b"]
a.sort!                   #=> ["a", "b", "c", "d", "e"]
a.sort! {|x,y| y <=> x }  #=> ["e", "d", "c", "b", "a"]
Информация

Более интересная и чаще используемая форма сортировки производится при помощи метода Enumerable#sort_by

Array#to_a[править]


array.to_a #=> array


Возвращает указатель на self. Если вызывается от потомка классаArray, то конвертирует указанный объект в массив (объект классаArray).

Array#to_ary[править]


array.to_ary #=> array

Возвращает указатель на self. По сути, ничего не делает.

Array#to_s[править]


array.to_s  #=> string

Возвращает результат self.join.

["a", "e", "i", "o"].to_s  #=> "aeio"

Array#transpose[править]


array.transpose #=> an_array

Подразумевает, что array является массивом массивов (то есть с размерностью больше, чем один) и меняет местами столбцы со строками (транспонирует).

a = [[1,2], [3,4], [5,6]]
a.transpose  #=> [[1, 3, 5], [2, 4, 6]]

Array#uniq[править]


array.uniq  #=> an_array

Возвращает новый массив, который получен из массива array путем удаления всех повторяющихся элементов (то есть остаются только «уникальные» элементы).

a = ["a", "a", "b", "b", "c"]
a.uniq   #=> ["a", "b", "c"]

Array#uniq![править]


array.uniq!  #=> array или nil

Удаляет из массива array все повторяющиеся элементы (то есть остаются только «uniq'альные элементы»). Возвращаетnil, если повторяющиеся элементы в массиве array отсутствовали.

a = ["a", "a", "b", "b", "c"]
a.uniq!  #=> ["a", "b", "c"]
b = ["a", "b", "c"]
b.uniq!  #=> nil

Array#unshift[править]


array.unshift(obj, ...)  #=> array

Добавляет элементы в начало массива array (со сдвигом вправо уже существующих).

a = ["b", "c", "d"]
a.unshift("a")   #=> ["a", "b", "c", "d"]
a.unshift(1, 2)  #=> [ 1, 2, "a", "b", "c", "d"]
a                #=> [ 1, 2, "a", "b", "c", "d"]

Array#values_at[править]


array.values_at(selector,... )  #=> an_array

Возвращает массив, который состоит из элементов массива array, которые соответствуют передаваемым селекторам. Селекторы могут быть целыми числами (индексами) или целочисленными диапазонами.

a = %w{ a b c d e f }
a.values_at(1, 3, 5)
a.values_at(1, 3, 5, 7)
a.values_at(-1, -3, -5, -7)
a.values_at(1..3, 2...5)
Информация

Для подобных целей также используются методы select и [] («батарейка»). Вот только в «батарейке» нельзя указывать несколько непоследовательных индексов или диапазонов, а select отбирает элементы по условию (а не по индексу)

Array#zip[править]


array.zip(arg, ...)                   #=> an_array
array.zip(arg, ...) {| arr | block }  #=> nil

Преобразует аргументы в массивы (при помощи методаto_a). Объединяет каждый элемент массива array с соответствующим массивом, переданным в качестве аргумента. В результате этого создается двумерный массив с array.size строками и сn столбцами, гдеn — максимальная из длин аргументов-массивов. Если длина какого либо из аргументов-массивов меньшеn, то он расширяется до длиныn (дополняетсяnil). Если задан блок, то получаемые массивы передаются в блок в качестве параметра, иначе — возвращается двумерный массив.

a = [4, 5, 6]
b = [7, 8, 9]
[1,2,3].zip(a, b)  #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[1,2].zip(a,b)     #=> [[1, 4, 7], [2, 5, 8]]
a.zip([1,2],[8])   #=> [[4,1,8], [5,2,nil], [6,nil,nil]]
Информация

Обычно используется совместно с методом assoc, то естьzip подготавливает для него массив, по которому будет осуществляться ассоциация

Класс Bignum < Integer[править]

Классу Bignum принадлежат целые числа, которые не умещаются в диапазон класса Fixnum. Объекты класса Bignum создаются автоматически, когда результат вычислений превышает (по модулю) предельное значение класса Fixnum. Когда, в результате вычислений, объект класса Bignum уменьшается настолько, что его значение можно хранить в объекте класса Fixnum, то он автоматически преобразуется в Fixnum. Для обеспечения работы побитовых операций и метода [], объект класса Bignum следует рассматривать как двоичную последовательность бесконечной длины. В отличие от Fixnum, объекты класса Bignum передаются не непосредственно, а по ссылке.


Методы объекта

[], %, &, **, *, +, -@, -, /, <<, <=>, ==, >>, ^, abs, coerce, divmod, div, eql?, hash, modulo, power!, quo, rdiv, remainder, rpower, size, to_f, to_s, ||, ~

Bignum#%[править]


big % other         
big.modulo(other)   #-> numeric

Возвращает остаток от деления чис#-> numeric

1234567890 % 2      #-> 0
1234567890 % 1.2    #-> 4.56881898980299e-008
1234567890 % -2     #-> 0
Информация

Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации

Информация

Методы % и modulo — абсолютно идентичны, то есть являются именами одного и того же метода

Информация

Полезно посмотреть на методы **, +, -, / и *, которые имеют схожую функциональность

Bignum#&[править]


big & numeric   #->  integer

Побитовое И.

Bignum#*[править]


big * other  #-> numeric

Умножает число big на число other и возвращает результат.

1234567890 * 2      #-> 2469135780
1234567890 * 1.2    #-> 1481481468.0
1234567890 * -2     #-> -2469135780
Информация

Полезно посмотреть на методы **, +, -, / и %, которые имеют схожую функциональность

Bignum#**[править]


big ** other        #-> numeric
big.rpower(other)   #-> numeric

Возводит число big в степень other (которая может быть целым, дробным или любым другим числом). Результат может быть класса Fixnum, Bignum или Float.

123456789 ** 2      #-> 15241578750190521
123456789 ** 1.2    #-> 5126464716.09932
123456789 ** -2     #-> 6.5610001194102e-17
Информация

Полезно посмотреть на методы *, +, -, /, % и power!, которые имеют схожую функциональность

Информация

Методы ** и rpower — абсолютно идентичны, то есть являются именами одного и того же метода

Bignum#+[править]


big + other  #-> numeric

Складывает число big с числом other и возвращает результат.

1234567890 + 2      #-> 1234567892
1234567890 + 1.2    #-> 1234567891.2
1234567890 + (-2)   #-> 1234567888
Информация

Полезно посмотреть на методы **, *, -, / и %, которые имеют схожую функциональность

Bignum#-[править]


big - other  #-> numeric

Вычитает из числа big число other и возвращает результат.

1234567890 - 2      #-> 1234567888
1234567890 - 1.2    #-> 1234567888.8
1234567890 - (-2)   #-> 1234567892
Информация

Полезно посмотреть на методы **, +, *, / и %, которые имеют схожую функциональность

Bignum#-@[править]


-big   #->  other_big

Унарный минус (возвращает новый объект класса Bignum, значение которого равно 0-big)

Bignum#/[править]


big / other     #-> numeric
big.div(other)  #-> numeric

Делит число big на число other и возвращает результат.

1234567890 / 2      #-> 617283945
1234567890 / 1.2    #-> 1028806575.0
1234567890 / (-2)   #-> -617283945
Информация

Полезно посмотреть на методы **, *, -, +, % и quo, которые имеют схожую функциональность

Информация

Методы / и div — абсолютно идентичны, то есть являются именами одного и того же метода

Bignum#<<[править]


big << numeric   #->  integer

Побитовый сдвиг числа big влево на numeric позиций (вправо, если numeric меньше нуля).

Информация

Полезно посмотреть на метод >>, который имеет схожую функциональность

Bignum#<=>[править]


big <=> numeric   #-> -1, 0, +1

Сравнение — возвращает −1, 0 или +1, если значение числа big меньше, равно или больше значения числа numeric, соответственно. Это базис для тестов в примеси Comparable.

Bignum#[править]


big == obj  #-> true или false

Возвращает true, если число obj имеет такое же значение, что и число big. В отличие от метода eql?, приводит число obj к классу Bignum.

68719476736 == 68719476736.0   #-> true

Bignum#>>[править]


big >> numeric   #->  integer

Побитовый сдвиг числа big вправо на numeric позиций (влево, если numeric меньше нуля).

Информация

Полезно посмотреть на метод <<, который имеет схожую функциональность

Bignum#[][править]


big[n]   #-> 0, 1

Побитовый доступ — возвращает nый бит (виртуальный) двоичного представления числа big, где big[0] — младший значащий бит.

a = 9**15
50.downto(0) do |n|
  print a[n]
end

результат:

 000101110110100000111000011110010100111100010111001

Bignum#^[править]


big ^ numeric   #->  integer

Побитовое ИСКЛЮЧАЮЩЕЕ ИЛИ

Bignum#abs[править]


big.abs #-> bignum

Возвращает абсолютное значение числа big.

-1234567890987654321.abs   #-> 1234567890987654321

Bignum#coerce[править]


big.coerce(other)   #-> array

Возвращает массив, состоящий из чисел other и big, которые преобразованы к классу Bignum.

result = 1234567890.coerce( 1234 )   #-> [1234, 1234567890]
result[0]                            #-> 1234
result[0].class                      #-> Bignum

Bignum#div[править]


big / other     #-> numeric
big.div(other)  #-> numeric

Делит число big на число other и возвращает результат.

1234567890 / 2      #-> 617283945
1234567890 / 1.2    #-> 1028806575.0
1234567890 / (-2)   #-> -617283945
Информация

Полезно посмотреть на методы **, *, -, +, % и quo, которые имеют схожую функциональность

Информация

Методы / и div — абсолютно идентичны, то есть являются именами одного и того же метода

Bignum#divmod[править]


big.divmod(numeric)   #-> array

Информация

Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации

Bignum#eql?[править]


big.eql?(obj)   #-> true или false

Возвращает true, если число obj имеет такое же значение, что и число big. В отличие от метода ==, не занимается приведением типов.

68719476736.eql?(68719476736.0)   #-> false

Bignum#hash[править]


big.hash   #-> fixnum

Вычисляет контрольную сумму на основе значения числа big.

Bignum#modulo[править]


big % other         #-> numeric
big.modulo(other)   #-> numeric

Возвращает остаток от деления числа big на числоother.

Информация

Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации

Информация

Методы % и modulo — абсолютно идентичны, то есть являются именами одного и того же метода

Информация

Полезно посмотреть на методы **, +, -, / и *, которые имеют схожую функциональность

Bignum#power![править]


big.power!(other)   #-> numeric

Производит возведение числа fix в степень other.

1234567890.power!( 2 )    #-> 1524157875019052100
1234567890.power!( -2 )   #-> 6.5610001194102e-019
Информация

Полезно посмотреть на методы ** и rpower, которые имеют схожую функциональность

Bignum#quo[править]


big.quo(other)    #-> numeric
big.rdiv(other)   #-> numeric

Делит число big на число other и в качестве результата возвращает рациональное число.

1234567890.quo(7)   #-> Rational(1234567890, 7)
Информация

Полезно посмотреть на методы / и div, которые имеют схожую функциональность

Информация

Методы quo и rdiv — абсолютно идентичны, то есть являются именами одного и того же метода

Bignum#rdiv[править]


big.quo(other)    #-> numeric
big.rdiv(other)   #-> numeric

Делит число big на число other и в качестве результата возвращает рациональное число.

1234567890.rdiv(7)   #-> Rational(1234567890, 7)
Информация

Полезно посмотреть на методы / и div, которые имеют схожую функциональность

Информация

Методы quo и rdiv — абсолютно идентичны, то есть являются именами одного и того же метода

Bignum#remainder[править]


big.remainder(numeric)    #-> number

Возвращает остаток от деления числа big на число numeric.

-1234567890987654321.remainder(13731)      #-> -6966
-1234567890987654321.remainder(13731.24)   #-> -9906.22531493148
Информация

Полезно посмотреть на методы quo, rdiv, % и modulo, которые имеют схожую функциональность

Bignum#rpower[править]


big ** other        #-> numeric
big.rpower(other)   #-> numeric

Производит возведение числа big в степень other. Возвращает рациональное число, если результат рациональный (то есть, когда other < 0).

1234567890.power!( 2 )    #-> 1524157875019052100
1234567890.power!( -2 )   #-> Rational(1, 1524157875019052100)
Информация

Методы ** и rpower — абсолютно идентичны, то есть являются именами одного и того же метода

Информация

Полезно посмотреть на метод power!, который имеет схожую функциональность

Bignum#size[править]


big.size #-> integer

Возвращает количество байт машинного представления числа big.

(256**10 - 1).size   #-> 12
(256**20 - 1).size   #-> 20
(256**40 - 1).size   #-> 40

Bignum#to_f[править]


big.to_f   #-> float

Преобразует число big в число класса Float. Если число big не может быть преобразовано к классу Float, то возвращает бесконечность.

Информация

Полезно посмотреть на метод to_s, который имеет схожую функциональность

Bignum#to_s[править]


big.to_s(base=10)   #->  string

Возвращает строку, где число big имеет основание системы счисления равное base (между 2 и 36). По умолчанию base=10 (то есть десятичная система счисления).

12345654321.to_s         #-> "12345654321"
12345654321.to_s(2)      #-> "1011011111110110111011110000110001"
12345654321.to_s(8)      #-> "133766736061"
12345654321.to_s(16)     #-> "2dfdbbc31"
78546939656932.to_s(36)  #-> "rubyrules"
Информация

Полезно посмотреть на метод to_f, который имеет схожую функциональность

Bignum#|[править]


big | numeric   #->  integer

Побитовое ИЛИ.

Bignum#≈[править]


~big  #->  integer

Побитовое НЕ. Так как Bignum теоретически имеет бесконечную длину, то для вычисления результата берется число big на один бит длиннее старшего значащего бита (чтобы операция инверсии была обратимой).

sprintf("%X", ~0x499602d2)    #-> "-499602d3"
~~1234567890                  #-> 1234567890

Класс Class < Module[править]

Классы в Руби это уникальные объекты --- каждый из которых является экземпляром класса Class. Когда новый класс создается (обычно используется class Name ... end), объект типа Class создается и присваивается одноименной глобальной переменной (в данном случае Name). Когда вызывается Name.new для создания нового объекта, запускается метод new класса Class. Это можно продемонстрировать перегрузкой метода new в классе Class:

class Class
   alias oldNew  new
   def new(*args)
      print "Создается новый #{self.name}\n"
      oldNew(*args)
   end
end

class Name
end

n = Name.new

результат:

Создается новый Name

Классы, модули и объекты взаимосвязаны. На следующей диаграмме, вертикальными стрелками обозначено наследование, а круглыми скобками --- метаклассы. Все метаклассы это объекты класса `Class'.

                         +------------------+
                         |                  |
           Object---->(Object)              |
            ^  ^        ^  ^                |
            |  |        |  |                |
            |  |  +-----+  +---------+      |
            |  |  |                  |      |
            |  +-----------+         |      |
            |     |        |         |      |
     +------+     |     Module--->(Module)  |
     |            |        ^         ^      |
OtherClass-->(OtherClass)  |         |      |
                           |         |      |
                         Class---->(Class)  |
                           ^                |
                           |                |
                           +----------------+

Объявленные атрибуты будут доступны в пределах иерархии наследования, где каждый потомок получает копию атрибутов своих родителей, вместо истинного указателя на него. Это означает, что потомок может добавить элементы, для примера, в массив без тех дополнений которые он делит со своим родителем, элементами одного с ним уровня (имеющими общего родителя) или потомками, которые не похожи на правильные атрибуты уровня класса и которые разделены поперек всей иерархии


Методы класса

new

Методы объекта

allocate, inherited, new, superclass

Class::new[править]


Class.new(super_class=Object)   #->    a_class

Создание нового анонимного (безымянного) класса наследованного от super_class (или Object, если вызывается без параметров). Вы можете дать классу имя, присвоив его константе.

Class#allocate[править]


class.allocate   #->   obj

Выделяет место для нового объекта класса class. Возвращаемый объект является экземпляром класса class.

Class#inherited[править]


class.inherited( sub_class )

Вызывается Руби, когда происходит наследование от класса class. Новый подкласс передается в качестве параметра sub_class.

class Top
   def Top.inherited(sub)
      puts "Новый подкласс: #{sub}"
   end
end
  
class Middle < Top
end
  
class Bottom < Middle
end

результат:

Новый подкласс: Middle
Новый подкласс: Bottom

Class#new[править]


class.new(args, ...)    #->  obj

Вызывает allocate для создания нового объекта класса class, вызывается метод initialize, которому передается args. Этот метод вызывается каждый раз, когда создается объект при помощи метода .new.

Class#superclass[править]


class.superclass   #-> a_super_class или nil

Возвращает суперкласс (от которого произошло наследование) класса class, или nil.

File.superclass     #-> IO
IO.superclass       #-> Object
Object.superclass   #-> nil

Примесь Comparable[править]

Примесь Comparable используется классами, объекты которых должны сравниваться. Класс должен реализовать оператор <=>, который сравнивает полученные объекты и возвращает -1, 0, или +1, если левый объект меньше, равен или больше правого, соответственно. Comparable использует метод <=> в реализации остальных операторов сравнения (<, <=, ==, >= и >) и метода between?.

class SizeMatters
   include Comparable
   attr :str
   def <=>(anOther)
      str.size <=> anOther.str.size
   end
   def initialize(str)
      @str = str
   end
   def inspect
     @str
   end
end

s1 = SizeMatters.new("Z")
s2 = SizeMatters.new("YY")
s3 = SizeMatters.new("XXX")
s4 = SizeMatters.new("WWWW")
s5 = SizeMatters.new("VVVVV")

s1 < s2                       #-> true
s4.between?(s1, s3)           #-> false
s4.between?(s3, s5)           #-> true
[ s3, s2, s5, s4, s1 ].sort   #-> [Z, YY, XXX, WWWW, VVVVV]

Методы объекта

<=, <, ==, >=, >, between?

Comparable#<[править]


obj < other    #-> true или false

Сравнение двух объектов, основанное на результате вызова метода <=>, возвращает true если тот возвращает -1.

Comparable#<=[править]


obj <= other    #-> true или false

Сравнение двух объектов, основанное на результате вызова метода <=>, возвращает true если тот возвращает -1 или 0.

Comparable#==[править]


obj == other    #-> true или false

Сравнение двух объектов, основанное на результате вызова метода <=>, возвращает true если тот возвращает 0. Еще возвращает true если obj и other являются ссылками на один и тот же объект.

Comparable#>[править]


obj > other    #-> true или false

Сравнение двух объектов основанное на результате вызова метода <=>, возвращает true если тот возвращает 1.

Comparable#>=[править]


obj >= other    #-> true или false

Сравнение двух объектов, основанное на результате вызова метода <=>, возвращает true если тот возвращает 0 или 1.

Comparable#between?[править]


obj.between?(min, max)    #-> true или false

Возвращает false если obj <=> min меньше нуля или если obj <=> max больше нуля, true иначе.

3.between?(1, 5)               #-> true
6.between?(1, 5)               #-> false
'cat'.between?('ant', 'dog')   #-> true
'gnu'.between?('ant', 'dog')   #-> false

Класс Dir[править]

tmpdir - retrieve temporary directory path $Id: tmpdir.rb,v 1.5.2.1 2005/12/15 15:57:05 matz Exp $


Примеси

Enumerable (all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find, find_all, grep, group_by, include?, index_by, inject, map, max, member?, min, partition, reject, select, sort, sort_by, sum, to_a, to_set, zip),

Windows::DeviceIO (CTL_CODE, DeviceIoControl, FSCTL_SET_COMPRESSION, FSCTL_SET_SPARSE),

Windows::Directory (CreateDirectory, CreateDirectoryEx, CreateDirectoryExW, CreateDirectoryW, FindCloseChangeNotification, FindFirstChangeNotification, FindNextChangeNotification, GetCurrentDirectory, GetCurrentDirectoryW, ReadDirectoryChangesW, RemoveDirectory, RemoveDirectoryW, SetCurrentDirectory, SetCurrentDirectoryW),

Windows::Error (FormatMessage, FormatMessageW, GetLastError, SetErrorMode, SetLastError, SetLastErrorEx, get_last_error),

Windows::File (CopyFile, CopyFileEx, CreateFile, CreateHardLink, DecryptFile, DeleteFile, EncryptFile, GetBinaryType, GetFileAttributes, GetFileAttributesEx, GetFileSize, GetFileSizeEx, GetFileType, GetFullPathName, GetLongPathName, GetShortPathName, LockFile, LockFileEx, ReadFile, ReadFileEx, SetFileAttributes, UnlockFile, UnlockFileEx, WriteFile, WriteFileEx),

Windows::Shell (SHGetFolderPath, SHGetSpecialFolderLocation, SHGetSpecialFolderPath)

Константы

VERSION

Методы класса

[], chdir, chroot, create_junction, delete, empty?, entries, foreach, getwd, glob, junction?, mkdir, new, open, pwd, rmdir, tmpdir, unlink

Методы объекта

close, each, path, pos=, pos, read, rewind, seek, tell

Dir::[][править]


 Dir[ string ] => array

Похоже на вызов dir.glob(string,0).

Dir::chdir[править]


 Dir.chdir( [ string] ) => 0
 Dir.chdir( [ string] ) {| path | block }  => anObject

Сменяет текущую директорию процесса на указанную в строке. Если вызвано без аргументов, сменяется значение равное HOME, или LOGDIR. SystemCallError (вероятно Errno::ENOENT) появляется когда директории нет.. Если задан блок, ему передается имя нового текущей директории, а блок выполняется с ним в качестве текущей директории. Исходный рабочий каталог восстанавливается при выходе из блока. Возвращаемое значение chdir - это значение блока. Блоки chdir могут быть вложеными, но в многопоточной программе может вылезти ошибка, если поток попытается открыть блок chdir, а другой поток - один.

  Dir.chdir("/var/spool/mail")
  puts Dir.pwd
  Dir.chdir("/tmp") do
    puts Dir.pwd
    Dir.chdir("/usr") do
      puts Dir.pwd
    end
    puts Dir.pwd
  end
  puts Dir.pwd

производит:

  /var/spool/mail
  /tmp
  /usr
  /tmp
  /var/spool/mail

Dir::chroot[править]


 Dir.chroot( string ) => 0

Изменяет представление процесса корня файловой системы. Только уполномоченные процессы могут её использовать. Не на всех платформах доступна эта функция. На Unix системах, См. chroot(2) для детальной информации.

Dir::create_junction[править]


 Dir::create_junction(to, from)

Создает символическую ссылку to, связанную с существующим каталогом from. Если каталог уже существует, он должен быть пустым, иначе выдаст ошибку.

Dir::delete[править]


 Dir.delete( string ) => 0
 Dir.rmdir( string ) => 0
 Dir.unlink( string ) => 0

Удаляет указанную директорию. Вызывается ошибка SystemCallError если директория не пуста.

Dir::empty?[править]


 Dir::empty?(path)

Возвращает результат проверки пустоты директории path. Возвращает false если path это не директория, или имеет файлы отличающиеся от '.' или '..'.

Dir::entries[править]


 Dir.entries( dirname ) => array

Возвращает массив содержащий все имена файлов в указанной директории. Будет вызван SystemCallError если директории не существует.

  Dir.entries("testdir")   #=> [".", "..", "config.h", "main.rb"]

Dir::foreach[править]


 Dir.foreach( dirname ) {| filename | block }  => nil

Вызывает блок один раз для каждой записи в указанной директории, передавая имя файла каждой записи в качестве параметра в блок.

  Dir.foreach("testdir") {|x| puts "Got #{x}" }

производит:

  Got .
  Got ..
  Got config.h
  Got main.rb

Dir::getwd[править]


 Dir.getwd => string
 Dir.pwd => string

Возвращает путь к директории исполняемого процесса.

  Dir.chdir("/tmp")   #=> 0
  Dir.getwd           #=> "/tmp"

Dir::glob[править]


 Dir.glob( string, [flags] ) => array
 Dir.glob( string, [flags] ) {| filename | block }  => nil

Возвращает найденные имена файлов, расширяя шаблон, указанный в string, или как array, или как параметры блока. Обратите внимание, что этот шаблон не является регулярным выражением (он ближе к оболочке glob). См. File::fnmatch для обозначение параметра flags.

Соответствует любому файлу. Может быть ограничено другими значениями в glob.

* - будет соответствовать всем файлам;

c* - будет соответствовать всем файлам, начинающимся с c;

*c - будет соответствовать всем файлам, заканчивающимся на c;

c - будет соответствовать всем файлам, имеющими c (включая начальную или конечную).

Эквивалентно / .* /x в регулярном выражении. Соответствует рекурсивным каталогам. Соответствует любому знаку. Эквивалентно /.{1}/ в регулярном выражении. Соответствует любому символу в set. Ведет себя точно так же, как наборы символов в регулярном выражении, включая установление отрицания ([^a-z]). Соответствует литералам p или литералам q. Соответствующие литералы могут иметь длину более одного символа. Можно указать более двух литералов. Эквивалентно чередованию шаблонов в регулярном выражении.

Убирает следующий метасимвол.
  Dir["config.?"]                     #=> ["config.h"]
  Dir.glob("config.?")                #=> ["config.h"]
  Dir.glob("*.[a-z][a-z]")            #=> ["main.rb"]
  Dir.glob("*.[^r]*")                 #=> ["config.h"]
  Dir.glob("*.{rb,h}")                #=> ["main.rb", "config.h"]
  Dir.glob("*")                       #=> ["config.h", "main.rb"]
  Dir.glob("*", File::FNM_DOTMATCH)   #=> [".", "..", "config.h", "main.rb"]
  rbfiles = File.join("**", "*.rb")
  Dir.glob(rbfiles)                   #=> ["main.rb",
                                           "lib/song.rb",
                                           "lib/song/karaoke.rb"]
  libdirs = File.join("**", "lib")
  Dir.glob(libdirs)                   #=> ["lib"]
  librbfiles = File.join("**", "lib", "**", "*.rb")
  Dir.glob(librbfiles)                #=> ["lib/song.rb",
                                           "lib/song/karaoke.rb"]
  librbfiles = File.join("**", "lib", "*.rb")
  Dir.glob(librbfiles)                #=> ["lib/song.rb"]

Dir::junction?[править]


 Dir::junction?(path)

Возвращает является ли path соединением или нет.

Dir::mkdir[править]


 Dir.mkdir( string [, integer] ) => 0

Создает папку, имя которой указано в string, с разрешениями, заданными необязательным параметром как Integer. TРазрешения могут быть изменены значением File::umask, и игнорируются на NT. Вызывает SystemCallError если директория не может быть создана. См. Также обсуждение разрешений в документации по классу для File.

Dir::new[править]


 Dir.new( string ) -> aDir

Возвращает новый объект директории.

Dir::open[править]


 Dir.open( string ) => aDir
 Dir.open( string ) {| aDir | block } => anObject

Без блока, open это синоним к Dir::new. Если присутствует блок, он передается в Dir как параметр. Директория закрывается при окончании блока, и Dir::open возвращает значения блока.

Dir::pwd[править]


 Dir.getwd => string
 Dir.pwd => string

Возвращает путь к директории исполняемого процесса.

  Dir.chdir("/tmp")   #=> 0
  Dir.getwd           #=> "/tmp"

Dir::rmdir[править]


 Dir.delete( string ) => 0
 Dir.rmdir( string ) => 0
 Dir.unlink( string ) => 0

Удаляет указанную директорию. Вызывает субкласс SystemCallError если директория не пуста.

Dir::tmpdir[править]


 Dir::tmpdir()

Возвращает временный путь к файловой системе операционной системы.

Dir::unlink[править]


 Dir.delete( string ) => 0
 Dir.rmdir( string ) => 0
 Dir.unlink( string ) => 0

Удаляет указанную директорию. Вызывает подкласс SystemCallError если директория не пуста.

Dir#close[править]


 dir.close => nil

Закрывает директорию. Дальнейшие попытки вызова dir вызовут IOError.

  d = Dir.new("testdir")
  d.close   #=> nil

Dir#each[править]


 dir.each { |filename| block }  => dir

Вызывает блок к каждому содержимому директории, передает значение файла/папки как входной параметр.

  d = Dir.new("testdir")
  d.each  {|x| puts "Got #{x}" }

производит:

  Got .
  Got ..
  Got config.h
  Got main.rb

Dir#path[править]


 dir.path => string or nil

Возвращает значение директори записанной в dir.

  d = Dir.new("..")
  d.path   #=> ".."

Dir#pos[править]


 dir.pos => integer
 dir.tell => integer

Возвращает текущее положение в dir. См. также Dir#seek.

  d = Dir.new("testdir")
  d.tell   #=> 0
  d.read   #=> "."
  d.tell   #=> 12

Dir#pos=[править]


 dir.pos( integer ) => integer

Синоним для Dir#seek, но возвращает параметр положения.

  d = Dir.new("testdir")   #=> #<Dir:0x401b3c40>
  d.read                   #=> "."
  i = d.pos                #=> 12
  d.read                   #=> ".."
  d.pos = i                #=> 12
  d.read                   #=> ".."

Dir#read[править]


 dir.read => string or nil

Читает следующую запись из dir и возвращает ее как строку. Возвращает nil в конце потока.

  d = Dir.new("testdir")
  d.read   #=> "."
  d.read   #=> ".."
  d.read   #=> "config.h"

Dir#rewind[править]


 dir.rewind => dir

Переход dir в начало.

  d = Dir.new("testdir")
  d.read     #=> "."
  d.rewind   #=> #<Dir:0x401b3fb0>
  d.read     #=> "."

Dir#seek[править]


 dir.seek( integer ) => dir

Обращается к определенному месту в dir.integer должен быть значением, возвращаемым в Dir#tell.

  d = Dir.new("testdir")   #=> #<Dir:0x401b3c40>
  d.read                   #=> "."
  i = d.tell               #=> 12
  d.read                   #=> ".."
  d.seek(i)                #=> #<Dir:0x401b3c40>
  d.read                   #=> ".."

Dir#tell[править]


 dir.pos => integer
 dir.tell => integer

Возвращает текущее положение в dir. См. также Dir#seek.

  d = Dir.new("testdir")
  d.tell   #=> 0
  d.read   #=> "."
  d.tell   #=> 12

Примесь Enumerable[править]

Примесь Enumerable обеспечивает классы коллекций методами итерации(обхода), поиска и сортировки значений. Класс реализующий Enumerable должен определить метод each который вызывает (в yield) последовательно элементы коллекции. Если Enumerable#max, #min, или #sort необходимы, тогда объекты коллекции должны реализовывать оператор сравнения <=>, так как эти методы зависят от порядка элементов коллекции между друг другом.


Методы объекта

all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find_all, find, grep, group_by, include?, index_by, inject, map, max, member?, min, partition, reject, select, sort_by, sort, sum, to_a, to_set, zip

Enumerable#all?[править]


 enum.all? [{|obj| block } ]   => true or false

Передаёт в указанный блок каждый элемент коллекции. Метод возвращает true если блок ни разу не вернул false или nil. Если блок не задан, Руби добавляет неявный блок {|obj| obj} (в результате чего all? вернёт true только при условии, если ни один из элементов коллекции не оказался ни false ни nil.)

  %w{ ant bear cat}.all? {|word| word.length >= 3}   #=> true
  %w{ ant bear cat}.all? {|word| word.length >= 4}   #=> false
  [ nil, true, 99 ].all?                             #=> false

Enumerable#any?[править]


 enum.any? [{|obj| block } ]   => true or false

Передаёт в указанный блок каждый элемент коллекции. Метод вернёт true если блок хотя бы один раз вернул значение, отличное от false или nil. Если блок не задан, Руби добавляет неявный блок {|obj| obj} (в результате чего any? вернёт true если по крайней мере один из элементов коллекции не окажется ни false ни nil.

  %w{ ant bear cat}.any? {|word| word.length >= 3}   #=> true
  %w{ ant bear cat}.any? {|word| word.length >= 4}   #=> true
  [ nil, true, 99 ].any?                             #=> true

Enumerable#collect[править]


 enum.collect {| obj | block }  => array
 enum.map     {| obj | block }  => array

Возвращает новый массив с результатом обработки блоком каждого элемента в исходном массиве enum.

  (1..4).collect {|i| i*i }   #=> [1, 4, 9, 16]
  (1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]

Enumerable#detect[править]


 enum.detect(ifnone = nil) {| obj | block }  => obj or nil
 enum.find(ifnone = nil)   {| obj | block }  => obj or nil

Передаёт в указанный блок каждый элемент коллекции enum. Возвращает первый элемент enum, для которого результат выполнения block не является false. Если не найдено ни одного соответствия, возвращается значение параметра ifnone (если определён) либо nil

  (1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
  (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35

Enumerable#each_cons[править]


 each_cons(n) {...}

Выполняет указанный блок для каждого массива, составляемого из набора <n> последовательных элементов коллекции. Например:

   (1..10).each_cons(3) {|a| p a}
   # выведет следующее
   [1, 2, 3]
   [2, 3, 4]
   [3, 4, 5]
   [4, 5, 6]
   [5, 6, 7]
   [6, 7, 8]
   [7, 8, 9]
   [8, 9, 10]

Enumerable#each_slice[править]


 e.each_slice(n) {...}

Выполняет указанный блок для каждого подмассива из <n> элементов. Например:

   (1..10).each_slice(3) {|a| p a}
   # outputs below
   [1, 2, 3]
   [4, 5, 6]
   [7, 8, 9]
   [10]

Enumerable#each_with_index[править]


 enum.each_with_index {|obj, i| block }  -> enum

Для каждого элемента enum вызывает block с двумя аргументами - самим элементом и его индексом.

  hash = Hash.new
  %w(cat dog wombat).each_with_index {|item, index|
    hash[item] = index
  }
  hash   #=> {"cat"=>0, "wombat"=>2, "dog"=>1} 
    arr_result = []
   arr = ['cat', 'dog', 'wombat', 'horse']
   arr.each_with_index {|item, index| 
     arr_result << [item, index] 
   }
   arr_result #=> [ ['cat', 0], ['dog', 1], ['wombat', 2], ['horse', 3] ] 

Enumerable#entries[править]


enum.to_a      #=>    array
enum.entries   #=>    array

Возвращает массив, содержащий элементы enum.

(1..7).to_a                       #=> [1, 2, 3, 4, 5, 6, 7]
{ 'a'=>1, 'b'=>2, 'c'=>3 }.to_a   #=> [["a", 1], ["b", 2], ["c", 3]]

Enumerable#enum_cons[править]


 e.enum_cons(n)

Возвращает Enumerable::Enumerator.new(self, :each_cons, n).

Enumerable#enum_slice[править]


 e.enum_slice(n)

Возвращает Enumerable::Enumerator.new(self, :each_slice, n).

Enumerable#enum_with_index[править]


 enum_with_index

Возвращает Enumerable::Enumerator.new(self, :each_with_index).

Enumerable#find[править]


 enum.detect(ifnone = nil) {| obj | block }  => obj or nil
 enum.find(ifnone = nil)   {| obj | block }  => obj or nil

Передает в block каждый элемент enum. Возвращает первый элемент, для которого результат обработки block не false. Если не найдено ни одного соответствия, возвращается значение параметра ifnone (если определён) либо nil

  (1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
  (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35

Enumerable#find_all[править]


 enum.find_all {| obj | block }  => array
 enum.select   {| obj | block }  => array

Возвращает массив, содержащий все элементы enum, для которых результат обработки block не является false (см.также Enumerable#reject).

  (1..10).find_all {|i|  i % 3 == 0 }   #=> [3, 6, 9]

Enumerable#grep[править]


 enum.grep(pattern)                   => array
 enum.grep(pattern) {| obj | block }  => array

Для каждого элемента enum возвращает массив, для элементов которого выполняется условие Pattern === element. Если задан необязательный block, каждый элемент возвращённого массива обрабатывается блоком и сохраняется в возвращённом массиве.

  (1..100).grep 38..44   #=> [38, 39, 40, 41, 42, 43, 44]
  c = IO.constants
  c.grep(/SEEK/)         #=> ["SEEK_END", "SEEK_SET", "SEEK_CUR"]
  res = c.grep(/SEEK/) {|v| IO.const_get(v) }
  res                    #=> [2, 0, 1]

Enumerable#group_by[править]


 group_by() {|element| ...}

Собирает Enumerable во множества, сгруппированные по результату обработки блоком. Применим, к примеру, для группирования записей по дате. Например:

 latest_transcripts.group_by(&:day).each do |day, transcripts|
   p "#{day} -> #{transcripts.map(&:class) * ', '}"
 end
 "2006-03-01 -> Transcript"
 "2006-02-28 -> Transcript"
 "2006-02-27 -> Transcript, Transcript"
 "2006-02-26 -> Transcript, Transcript"
 "2006-02-25 -> Transcript"
 "2006-02-24 -> Transcript, Transcript"
 "2006-02-23 -> Transcript"

Enumerable#include?[править]


 enum.include?(obj)     => true or false
 enum.member?(obj)      => true or false

Возвращает true если хотя бы один из элементов enum окажется равен obj. Равенство проверяется оператором ==.

  IO.constants.include? "SEEK_SET"          #=> true
  IO.constants.include? "SEEK_NO_FURTHER"   #=> false

Enumerable#index_by[править]


 index_by() {|elem| ...}

Преобразует Enumerable в Hash. Например:

 people.index_by(&:login)
   => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
 people.index_by { |person| "#{person.first_name} #{person.last_name}" }
   => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}

Enumerable#inject[править]


 enum.inject(initial) {| memo, obj | block }  => obj
 enum.inject          {| memo, obj | block }  => obj

Обрабатывает элементы enum применяя к ним блок, принимающий два параметра - аккумулятор (memo) и обрабатываемый элемент. На каждом шаге аккумулятору memo присваивается значение, возвращенное блоком. Первая форма позволяет присвоить аккумулятору некоторое исходное значение. Вторая форма в качестве исходного значения аккумулятора использует первый элемент коллекции (пропуская этот элемент при проходе).

  # Сложение нескольких чисел
  (5..10).inject {|sum, n| sum + n }              #=> 45
  # Умножение нескольких чисел
  (5..10).inject(1) {|product, n| product * n }   #=> 151200
  # Нахождение наиболее длинного слова
  longest = %w{ cat sheep bear }.inject do |memo,word|
     memo.length > word.length ? memo : word
  end
  longest                                         #=> "sheep"
  # Вычисление длины наиболее длинного слова
  longest = %w{ cat sheep bear }.inject(0) do |memo,word|
     memo >= word.length ? memo : word.length
  end
  longest                                         #=> 5

Enumerable#map[править]


 enum.collect {| obj | block }  => array
 enum.map     {| obj | block }  => array

Возвращает новый массив с результатами однократной обработки блоком block каждого элемента enum.

  (1..4).collect {|i| i*i }   #=> [1, 4, 9, 16]
  (1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]

Enumerable#max[править]


 enum.max                   => obj
 enum.max {|a,b| block }    => obj

Возвращает элемент enum с максимальным значением. Первая форма предполагает что все элементы являются Comparable. Вторая использует блок, возвращающий a <=> b.

  a = %w(albatross dog horse)
  a.max                                  #=> "horse"
  a.max {|a,b| a.length <=> b.length }   #=> "albatross"

Enumerable#member?[править]


 enum.include?(obj)     => true или false
 enum.member?(obj)      => true или false

Возвращает true если один из членов перечисления равен obj. Соответствие проверяется с использованием ==.

  IO.constants.include? "SEEK_SET"          #=> true
  IO.constants.include? "SEEK_NO_FURTHER"   #=> false

Enumerable#min[править]


 enum.min                    => obj
 enum.min {| a,b | block }   => obj

Возвращает элемент enum с минимальным значением. Первая форма предполагает что все элементы являются Comparable. Вторая использует блок, возвращающий a <=>

  a = %w(albatross dog horse)
  a.min                                  #=> "albatross"
  a.min {|a,b| a.length <=> b.length }   #=> "dog"

Enumerable#partition[править]


 enum.partition {| obj | block }  => [ true_array, false_array ]

Возвращает два массива. Первый содержит элементы enum, для которых результат обработки блока является true, а второй - все остальные элементы enum.

  (1..6).partition {|i| (i&1).zero?}   #=> [[2, 4, 6], [1, 3, 5]]

Enumerable#reject[править]


 enum.reject {| obj | block }  => array

Возвращает массив, содержащий все элементы enum, для которых результат обработки block является false (см.также Enumerable#find_all). Иными словами выталкивает из массива все элементы обработав которые блок вернет истину. Избавиться от свидетелей.

  (1..10).reject {|i|  i % 3 == 0 }   #=> [1, 2, 4, 5, 7, 8, 10]

Enumerable#select[править]


 enum.find_all {| obj | block }  => array
 enum.select   {| obj | block }  => array

Возвращает массив, содержащий все элементы enum, для которых результат обработки block не является false (см.также Enumerable#reject).

  (1..10).find_all {|i|  i % 3 == 0 }   #=> [3, 6, 9]

Enumerable#sort[править]


 enum.sort                     => array
 enum.sort {| a, b | block }   => array

Возвращает массив элементов enum, отсортированных либо собственным методом <=>, либо обработанных блоком. Блок возвращает -1, 0, or +1 в зависимости от результата сравнения a и b. Т.к. в Ruby 1.8, метод Enumerable#sort_by реализован на основе преобразования Шварца, он полезен для вычисления ключей или когда операции сравнения весьма ресурсоёмки.

  %w(rhea kea flea).sort         #=> ["flea", "kea", "rhea"]
  (1..10).sort {|a,b| b <=> a}   #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Enumerable#sort_by[править]


 enum.sort_by {| obj | block }    => array

Сортирует enum используя набор ключей, полученных обработкой элементов enum заданным блоком.

  %w{ apple pear fig }.sort_by {|word| word.length}
               #=> ["fig", "pear", "apple"]

Текущая реализация sort_by генерирует массив кортежей, содержащих исходную коллекцию элементов и вычисленное значение. Это делает метод sort_by существенно затратным когда наборы ключей просты.

  require 'benchmark'
  include Benchmark
  
  a = (1..100000).map {rand(100000)}
  
  bm(10) do |b|
    b.report("Sort")    { a.sort }
    b.report("Sort by") { a.sort_by {|a| a} }
  end

вывод:

  user     system      total        real
  Sort        0.180000   0.000000   0.180000 (  0.175469)
  Sort by     1.980000   0.040000   2.020000 (  2.013586)

Однако рассмотрим случай, когда сравнение ключей является нетривиальной операцией. Следующий код сортирует несколько файлов по времени модификации используя основной метод sort.

  files = Dir["*"]
  sorted = files.sort {|a,b| File.new(a).mtime <=> File.new(b).mtime}
  sorted   #=> ["mon", "tues", "wed", "thurs"]

Такая сортирвка неэффективна: для каждой операции сравнения генерируется два новых объекта File. Немного лучший способ - использовать метод Kernel#test для генерации времени модификации напрямую.

  files = Dir["*"]
  sorted = files.sort { |a,b|
    test(?M, a) <=> test(?M, b)
  }
  sorted   #=> ["mon", "tues", "wed", "thurs"]

Это всё ещё порождает множество ненужных объектов Time. Более эффективный метод - кеширование ключей сортировки (в данном случае времени модификации) перед сортировкой. Пользователи Perl часто называют этот метод преобразованием Шварца. Мы создаем временный массив, в котором каждый элемент - это массив, содержащий наши ключи сортировки и имя файла. Сортируем этот массив и извлекаем из результата имя файла.

  sorted = Dir["*"].collect { |f|
     [test(?M, f), f]
  }.sort.collect { |f| f[1] }
  sorted   #=> ["mon", "tues", "wed", "thurs"]

Это в точности то, что реализовано внутри sort_by.

  sorted = Dir["*"].sort_by {|f| test(?M, f)}
  sorted   #=> ["mon", "tues", "wed", "thurs"]

Enumerable#sum[править]


 sum(identity = 0, &block)

Вычисляет сумму элементов. напимер:

payments.sum { |p| p.price * p.tax_rate }
payments.sum(&:price)

Пример выше равнозначен payments.inject { |sum, p| sum + p.price } Также вычисляет суммы без использования блока:

 [5, 15, 10].sum # => 30

Значение по умолчанию (сумма пустого списка) равна нулю. Но это можно переопределить:

   [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)

Enumerable#to_a[править]


 enum.to_a      =>    array
 enum.entries   =>    array

Возвращает массив, содержащий элементы enum.

  (1..7).to_a                       #=> [1, 2, 3, 4, 5, 6, 7]
  { 'a'=>1, 'b'=>2, 'c'=>3 }.to_a   #=> [["a", 1], ["b", 2], ["c", 3]]

Enumerable#to_set[править]


 to_set(klass = Set, *args, &block)

Создает набор из Enumerable объекта с указанными аргументами. Для использования метода необходим require "set".

Enumerable#zip[править]


 enum.zip(arg, ...)                   => array
 enum.zip(arg, ...) {|arr| block }    => nil

Преобразует любые элементы в массивы, затем объединяет элементы enum с соответствующими элементами каждого из аргументов. Генерируется последовательность enum#size n-элементных массивов, где n - количество аргументов (1 или более). Если размер любого аргумента менее enum#size, то присваивается nil. Если задан блок, то он обрабатывает каждый результирующий массив. Иначе возвращается массив массивов.

  a = [ 4, 5, 6 ]
  b = [ 7, 8, 9 ]
  (1..3).zip(a, b)      #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
  "cat\ndog".zip([1])   #=> [["cat\n", 1], ["dog", nil]]
  (1..3).zip            #=> [[1], [2], [3]]

Класс FalseClass[править]

Глобальное значение false является единственным экземпляром класса FalseClass и означает логическое «НЕТ» в алгебре логики. Класс содержит операторы, которые позволяют false корректно вести себя в логических выражениях.


Методы объекта

&, ^, to_s, ||

FalseClass#&[править]


false & obj   #-> false
nil & obj     #-> false

Логическое «И» всегда возвращает false. obj всегда вычисляется, так как является аргументом метода. В этом случае нет никакого сокращенного вычисления.

FalseClass#^[править]


false ^ obj    #-> true или false
nil   ^ obj    #-> true или false

Логическое «ИЛИ НЕ». Если obj равен nil или false, возвращает false; иначе возвращает true.

FalseClass#to_s[править]


false.to_s   #->  "false"

Всегда возвращает строку "false".

FalseClass#|[править]


false | obj   #->   true или false
nil   | obj   #->   true или false

Логическое «ИЛИ» возвращает false, если obj равен nil или false; true иначе.

Класс File[править]

ftools adds several (class, not instance) methods to the File class, for copying, moving, deleting, installing, and comparing files, as well as creating a directory path. See the File class for details. FileUtils contains all or nearly all the same functionality and more, and is a recommended option over ftools When you

 require 'ftools'

then the File class aquires some utility methods for copying, moving, and deleting files, and more. See the method descriptions below, and consider using FileUtils as it is more comprehensive.


Примеси

Windows::DeviceIO (CTL_CODE, DeviceIoControl, FSCTL_SET_COMPRESSION, FSCTL_SET_SPARSE),

Windows::Error (FormatMessage, FormatMessageW, GetLastError, SetErrorMode, SetLastError, SetLastErrorEx, get_last_error),

Windows::File (CopyFile, CopyFileEx, CreateFile, CreateHardLink, DecryptFile, DeleteFile, EncryptFile, GetBinaryType, GetFileAttributes, GetFileAttributesEx, GetFileSize, GetFileSizeEx, GetFileType, GetFullPathName, GetLongPathName, GetShortPathName, LockFile, LockFileEx, ReadFile, ReadFileEx, SetFileAttributes, UnlockFile, UnlockFileEx, WriteFile, WriteFileEx),

Windows::Limits (),

Windows::Security (AddAce, CopySid, GetAce, GetFileSecurity, GetLengthSid, GetSecurityDescriptorControl, GetSecurityDescriptorDacl, InitializeAcl, InitializeSecurityDescriptor, LookupAccountName, LookupAccountSid, SetFileSecurity, SetSecurityDescriptorDacl)

Константы

ADD, ALT_SEPARATOR, ARCHIVE, BUFSIZE, CHANGE, COMPRESSED, CONTENT_INDEXED, FULL, HIDDEN, INDEXED, MAX_PATH, NORMAL, OFFLINE, PATH_SEPARATOR, READ, READONLY, SECURITY_RIGHTS, SEPARATOR, SYSTEM, Separator, TEMPORARY, VERSION

Методы класса

archive?, atime, attributes, basename, blksize, blockdev?, catname, chardev?, chmod, chown, compare, compressed?, copy, ctime, decrypt, delete, directory?, dirname, encrypted?, encrypt, executable?, executable_real?, exist?, exists?, expand_path, extname, file?, fnmatch?, fnmatch, ftype, get_permissions, grpowned?, hidden?, identical?, indexed?, install, join, lchmod, lchown, link, long_path, lstat, makedirs, move, mtime, new, normal?, offline?, owned?, pipe?, readable?, readable_real?, readlink, readonly?, remove_attributes, rename, reparse_point?, safe_unlink, securities, set_attributes, set_permissions, setgid?, setuid?, short_path, size?, size, socket?, sparse?, split, stat, sticky?, symlink?, symlink, syscopy, system?, temporary?, truncate, umask, unlink, utime, writable?, writable_real?, zero?

Методы объекта

archive=, atime, chmod, chown, compressed=, content_indexed=, ctime, flock, hidden=, indexed=, lstat, mtime, normal=, o_chmod, offline=, path, readonly=, sparse=, stat, system=, temporary=, truncate

File::archive?[править]


 File::archive?(file)

Возвращает true если файл или директория являются архивом. Приложения используют этот атрибут для маркировки файлов для резервного копирования или удаления.

File::atime[править]


 File.atime(file_name)  =>  time

Возвращает последнее время доступа для указанного файла как объект Time.

  File.atime("testfile")   #=> Wed Apr 09 08:51:48 CDT 2003

File::attributes[править]


 File::attributes(file)

Возвращает массив строк с указанием атрибутов для этого файла. Возможные значения: архив сжатый каталог зашифрованный скрытый индексированный нормальный автономный только чтнение точка повторной обработки разреженная система временная Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, используя метод: File::basename

File::blksize[править]


 File::blksize(file)

Возвращает блок файловой системы. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, используя метод: File::blockdev?

File::catname[править]


 File::catname(from, to)

If to is a valid directory, from will be appended to to, adding and escaping backslashes as necessary. Otherwise, to will be returned. Useful for appending from to to only if the filename was not specified in to. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, используя метод: : File::chardev?

File::chmod===[править]


 File::chmod(mode, *files)

Changes permission bits on files to the bit pattern represented by mode. If the last parameter isn't a String, verbose mode will be enabled.

 File.chmod 0755, 'somecommand'
 File.chmod 0644, 'my.rb', 'your.rb', true

File::chown[править]


 File.chown(owner_int, group_int, file_name,... ) -> integer

Changes the owner and group of the named file(s) to the given numeric owner and group id's. Only a process with superuser privileges may change the owner of a file. The current owner of a file may change the file's group to any group to which the owner belongs. A nil or -1 owner or group id is ignored. Returns the number of files processed.

  File.chown(nil, 100, "testfile")

File::compare[править]


 File::compare(from, to, verbose = false)

Returns true if and only if the contents of files from and to are identical. If verbose is true, from <=> to is printed.

File::compressed?[править]


 File::compressed?(file)

Returns true if the file or directory is compressed. For a file, this means that all of the data in the file is compressed. For a directory, this means that compression is the default for newly created files and subdirectories.

File::copy[править]


 File::copy(from, to, verbose = false)

Copies a file from to to using #syscopy. If to is a directory, copies from to to/from. If verbose is true, from -> to is printed.

File::ctime[править]


 File.ctime(file_name)  => time

Returns the change time for the named file (the time at which directory information about the file was changed, not the file itself).

  File.ctime("testfile")   #=> Wed Apr 09 08:53:13 CDT 2003

File::decrypt[править]


 File::decrypt(file)

Decrypts an encrypted file or directory. The caller must have the FILE_READ_DATA, FILE_WRITE_DATA, FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES, and SYNCHRONIZE access rights. Requires exclusive access to the file being decrypted, and will fail if another process is using the file. If the file is not encrypted an error is NOT raised. Windows 2000 or later only.

File::delete[править]


 File.delete(file_name, ...)  => integer
 File.unlink(file_name, ...)  => integer

Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. See also Dir::rmdir.

File::directory?[править]


 File.directory?(file_name)   =>  true or false

Returns true if the named file is a directory, false otherwise.

  File.directory?(".")

Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

File::dirname, File::dirname

File::encrypt[править]


 File::encrypt(file)

Encrypts a file or directory. All data streams in a file are encrypted. All new files created in an encrypted directory are encrypted. The caller must have the FILE_READ_DATA, FILE_WRITE_DATA, FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES, and SYNCHRONIZE access rights. Requires exclusive access to the file being encrypted, and will fail if another process is using the file. If the file is compressed, EncryptFile will decompress the file before encrypting it. Windows 2000 or later only.

File::encrypted?[править]


 File::encrypted?(file)

Returns true if the file or directory is encrypted. For a file, this means that all data in the file is encrypted. For a directory, this means that encryption is the default for newly created files and subdirectories.

File::executable?[править]


 File.executable?(file_name)   => true or false

Returns true if the named file is executable by the effective user id of this process.

File::executable_real?[править]


 File.executable_real?(file_name)   => true or false

Returns true if the named file is executable by the real user id of this process.

File::exist?[править]


 File.exist?(file_name)    =>  true or false
 File.exists?(file_name)   =>  true or false    (obsolete)

Return true if the named file exist

File::exists?[править]


 File.exist?(file_name)    =>  true or false
 File.exists?(file_name)   =>  true or false    (obsolete)

Return true if the named file exists. Метод возвращает true , если указанный файл file_name существует

File::expand_path[править]


 File.expand_path(file_name [, dir_string] ) -> abs_file_name

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a ``~, which expands to the process owner's home directory (the environment variable HOME must be set correctly). ``~user expands to the named user's home directory.

  File.expand_path("~oracle/bin")           #=> "/home/oracle/bin"
  File.expand_path("../../bin", "/tmp/x")   #=> "/bin"

File::extname[править]


 File.extname(path) -> string

Returns the extension (the portion of file name in path after the period).

  File.extname("test.rb")         #=> ".rb"
  File.extname("a/b/d/test.rb")   #=> ".rb"
  File.extname("test")            #=> ""
  File.extname(".profile")        #=> ""

File::file?[править]


 File.file?(file_name)   => true or false

Returns true if the named file exists and is a regular file.

File::fnmatch[править]


 File.fnmatch( pattern, path, [flags] ) => (true or false)
 File.fnmatch?( pattern, path, [flags] ) => (true or false)

Returns true if path matches against pattern The pattern is not a regular expression; instead it follows rules similar to shell filename globbing. It may contain the following metacharacters:

Matches any file. Can be restricted by other values in the glob. * will match all files; c* will match all files beginning with c; *c will match all files ending with c; and c will match all files that have c in them (including at the beginning or end). Equivalent to / .* /x in regexp. Matches any one character. Equivalent to /.{1}/ in regexp. Matches any one character in set. Behaves exactly like character sets in Regexp, including set negation ([^a-z]).

Escapes the next metacharacter.

flags is a bitwise OR of the FNM_xxx parameters. The same glob pattern and flags are used by Dir::glob.

  File.fnmatch('cat',       'cat')        #=> true
  File.fnmatch('cat',       'category')   #=> false
  File.fnmatch('c{at,ub}s', 'cats')       #=> false
  File.fnmatch('c{at,ub}s', 'cubs')       #=> false
  File.fnmatch('c{at,ub}s', 'cat')        #=> false
  File.fnmatch('c?t',    'cat')                       #=> true
  File.fnmatch('c\?t',   'cat')                       #=> false
  File.fnmatch('c??t',   'cat')                       #=> false
  File.fnmatch('c*',     'cats')                      #=> true
  File.fnmatch('c/ * FIXME * /t', 'c/a/b/c/t')                 #=> true
  File.fnmatch('c*t',    'cat')                       #=> true
  File.fnmatch('c\at',   'cat')                       #=> true
  File.fnmatch('c\at',   'cat', File::FNM_NOESCAPE)   #=> false
  File.fnmatch('a?b',    'a/b')                       #=> true
  File.fnmatch('a?b',    'a/b', File::FNM_PATHNAME)   #=> false
  File.fnmatch('*',   '.profile')                            #=> false
  File.fnmatch('*',   '.profile', File::FNM_DOTMATCH)        #=> true
  File.fnmatch('*',   'dave/.profile')                       #=> true
  File.fnmatch('*',   'dave/.profile', File::FNM_DOTMATCH)   #=> true
  File.fnmatch('*',   'dave/.profile', File::FNM_PATHNAME)   #=> false
  File.fnmatch('* / FIXME *', 'dave/.profile', File::FNM_PATHNAME)   #=> false
  STRICT = File::FNM_PATHNAME | File::FNM_DOTMATCH
  File.fnmatch('* / FIXME *', 'dave/.profile', STRICT)               #=> true

File::fnmatch?[править]


 File.fnmatch( pattern, path, [flags] ) => (true or false)
 File.fnmatch?( pattern, path, [flags] ) => (true or false)

Returns true if path matches against pattern The pattern is not a regular expression; instead it follows rules similar to shell filename globbing. It may contain the following metacharacters:

Matches any file. Can be restricted by other values in the glob. * will match all files; c* will match all files beginning with c; *c will match all files ending with c; and c will match all files that have c in them (including at the beginning or end). Equivalent to / .* /x in regexp. Matches any one character. Equivalent to /.{1}/ in regexp. Matches any one character in set. Behaves exactly like character sets in Regexp, including set negation ([^a-z]).

Escapes the next metacharacter.

flags is a bitwise OR of the FNM_xxx parameters. The same glob pattern and flags are used by Dir::glob.

  File.fnmatch('cat',       'cat')        #=> true
  File.fnmatch('cat',       'category')   #=> false
  File.fnmatch('c{at,ub}s', 'cats')       #=> false
  File.fnmatch('c{at,ub}s', 'cubs')       #=> false
  File.fnmatch('c{at,ub}s', 'cat')        #=> false
  File.fnmatch('c?t',    'cat')                       #=> true
  File.fnmatch('c\?t',   'cat')                       #=> false
  File.fnmatch('c??t',   'cat')                       #=> false
  File.fnmatch('c*',     'cats')                      #=> true
  File.fnmatch('c/ * FIXME * /t', 'c/a/b/c/t')                 #=> true
  File.fnmatch('c*t',    'cat')                       #=> true
  File.fnmatch('c\at',   'cat')                       #=> true
  File.fnmatch('c\at',   'cat', File::FNM_NOESCAPE)   #=> false
  File.fnmatch('a?b',    'a/b')                       #=> true
  File.fnmatch('a?b',    'a/b', File::FNM_PATHNAME)   #=> false
  File.fnmatch('*',   '.profile')                            #=> false
  File.fnmatch('*',   '.profile', File::FNM_DOTMATCH)        #=> true
  File.fnmatch('*',   'dave/.profile')                       #=> true
  File.fnmatch('*',   'dave/.profile', File::FNM_DOTMATCH)   #=> true
  File.fnmatch('*',   'dave/.profile', File::FNM_PATHNAME)   #=> false
  File.fnmatch('* / FIXME *', 'dave/.profile', File::FNM_PATHNAME)   #=> false
  STRICT = File::FNM_PATHNAME | File::FNM_DOTMATCH
  File.fnmatch('* / FIXME *', 'dave/.profile', STRICT)               #=> true

File::ftype[править]


 File.ftype(file_name)   => string

Identifies the type of the named file; the return string is one of ``file, ``directory, ``characterSpecial, ``blockSpecial, ``fifo, ``link, ``socket, or ``unknown.

  File.ftype("testfile")            #=> "file"
  File.ftype("/dev/tty")            #=> "characterSpecial"
  File.ftype("/tmp/.X11-unix/X0")   #=> "socket"

File::get_permissions[править]


 File::get_permissions(file, host=nil)

Returns a hash describing the current file permissions for the given file. The account name is the key, and the value is an integer representing an or'd value that corresponds to the security permissions for that file. To get a human readable version of the permissions, pass the value to the +File.securities+ method.

File::grpowned?[править]


 File.grpowned?(file_name)   => true or false

Returns true if the named file exists and the effective group id of the calling process is the owner of the file. Returns false on Windows.

File::hidden?[править]


 File::hidden?(file)

Returns true if the file or directory is hidden. It is not included in an ordinary directory listing.

File::identical?[править]


 File.identical?(file_1, file_2)   =>  true or false

Returns true if the named files are identical.

   open("a", "w") {}
   p File.identical?("a", "a")      #=> true
   p File.identical?("a", "./a")    #=> true
   File.link("a", "b")
   p File.identical?("a", "b")      #=> true
   File.symlink("a", "c")
   p File.identical?("a", "c")      #=> true
   open("d", "w") {}
   p File.identical?("a", "d")      #=> false

File::indexed?[править]


 File::indexed?(file)

Returns true if the file or directory is indexed by the content indexing service.

File::install[править]


 File::install(from, to, mode = nil, verbose = false)

If src is not the same as dest, copies it and changes the permission mode to mode. If dest is a directory, destination is dest/src. If mode is not set, default is used. If verbose is set to true, the name of each file copied will be printed.

File::join[править]


 File.join(string, ...) -> path

Returns a new string formed by joining the strings using File::SEPARATOR.

  File.join("usr", "mail", "gumby")   #=> "usr/mail/gumby"

File::lchmod[править]


 File.lchmod(mode_int, file_name, ...)  => integer

Equivalent to File::chmod, but does not follow symbolic links (so it will change the permissions associated with the link, not the file referenced by the link). Often not available.

File::lchown[править]


 file.lchown(owner_int, group_int, file_name,..) => integer

Equivalent to File::chown, but does not follow symbolic links (so it will change the owner associated with the link, not the file referenced by the link). Often not available. Returns number of files in the argument list.

File::link[править]


 File.link(old_name, new_name)    => 0

Creates a new name for an existing file using a hard link. Will not overwrite new_name if it already exists (raising a subclass of SystemCallError). Not available on all platforms.

  File.link("testfile", ".testfile")   #=> 0
  IO.readlines(".testfile")[0]         #=> "This is line one\n"

File::long_path[править]


 File::long_path(file)

Returns file in long format. For example, if 'SOMEFI~1.TXT' was the argument provided, and the short representation for 'somefile.txt', then this method would return 'somefile.txt'. Note that certain file system optimizations may prevent this method from working as expected. In that case, you will get back the file name in 8.3 format. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

File::lstat, File::lstat===File::makedirs===


 File::makedirs(*dirs)

Creates a directory and all its parent directories. For example,

   File.makedirs '/usr/lib/ruby'

causes the following directories to be made, if they do not exist.

   * /usr
   * /usr/lib
   * /usr/lib/ruby

You can pass several directories, each as a parameter. If the last parameter isn't a String, verbose mode will be enabled.

File::move[править]


 File::move(from, to, verbose = false)

Moves a file from to to using #syscopy. If to is a directory, copies from from to to/from. If verbose is true, from -> to is printed.

File::mtime[править]


 File.mtime(file_name)  =>  time

Returns the modification time for the named file as a Time object.

  File.mtime("testfile")   #=> Tue Apr 08 12:58:04 CDT 2003

File::new[править]


 File.new(filename, mode="r")            => file
 File.new(filename [, mode [, perm]])    => file

Opens the file named by filename according to mode (default is ``r) and returns a new File object. See the description of class IO for a description of mode. The file mode may optionally be specified as a Fixnum by or-ing together the flags (O_RDONLY etc, again described under IO). Optional permission bits may be given in perm. These mode and permission bits are platform dependent; on Unix systems, see open(2) for details.

  f = File.new("testfile", "r")
  f = File.new("newfile",  "w+")
  f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)

File::normal?[править]


 File::normal?(file)

Returns true if the file or directory has no other attributes set.

File::offline?[править]


 File::offline?(file)

Returns true if the data of the file is not immediately available. This attribute indicates that the file data has been physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not arbitrarily change this attribute.

File::owned?[править]


 File.owned?(file_name)   => true or false

Returns true if the named file exists and the effective used id of the calling process is the owner of the file.

File::pipe?[править]


 File.pipe?(file_name)   =>  true or false

Returns true if the named file is a pipe.

File::readable?[править]


 File.readable?(file_name)   => true or false

Returns true if the named file is readable by the effective user id of this process.

File::readable_real?[править]


 File.readable_real?(file_name)   => true or false

Returns true if the named file is readable by the real user id of this process.

File::readlink[править]


 File.readlink(link_name) -> file_name

Returns the name of the file referenced by the given link. Not available on all platforms.

  File.symlink("testfile", "link2test")   #=> 0
  File.readlink("link2test")              #=> "testfile"

File::readonly?[править]


 File::readonly?(file)

Returns true if The file or directory is read-only. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.

File::remove_attributes[править]


 File::remove_attributes(file, flags)

Removes the file attributes based on the given (numeric) flags.

File::rename[править]


 File.rename(old_name, new_name)   => 0

Renames the given file to the new name. Raises a SystemCallError if the file cannot be renamed.

  File.rename("afile", "afile.bak")   #=> 0

File::reparse_point?[править]


 File::reparse_point?(file)

Returns true if the file or directory has an associated reparse point. A reparse point is a collection of user defined data associated with a file or directory. For more on reparse points, search http://msdn.microsoft.com.

File::safe_unlink[править]


 File::safe_unlink(*files)

Removes a list of files. Each parameter should be the name of the file to delete. If the last parameter isn't a String, verbose mode will be enabled. Returns the number of files deleted.

File::securities[править]


 File::securities(mask)

Returns an array of human-readable strings that correspond to the permission flags.

File::set_attributes[править]


 File::set_attributes(file, flags)

Sets the file attributes based on the given (numeric) flags. This does not remove existing attributes, it merely adds to them.

File::set_permissions[править]


 File::set_permissions(file, perms)

Sets the file permissions for the given file name. The 'permissions' argument is a hash with an account name as the key, and the various permission constants as possible values. The possible constant values are: FILE_READ_DATA FILE_WRITE_DATA FILE_APPEND_DATA FILE_READ_EA FILE_WRITE_EA FILE_EXECUTE FILE_DELETE_CHILD FILE_READ_ATTRIBUTES FILE_WRITE_ATTRIBUTES STANDARD_RIGHTS_ALL FULL READ ADD CHANGE DELETE READ_CONTROL WRITE_DAC WRITE_OWNER SYNCHRONIZE STANDARD_RIGHTS_REQUIRED STANDARD_RIGHTS_READ STANDARD_RIGHTS_WRITE STANDARD_RIGHTS_EXECUTE STANDARD_RIGHTS_ALL SPECIFIC_RIGHTS_ALL ACCESS_SYSTEM_SECURITY MAXIMUM_ALLOWED GENERIC_READ GENERIC_WRITE GENERIC_EXECUTE GENERIC_ALL

File::setgid?[править]


 File.setgid?(file_name)   =>  true or false

Returns true if the named file has the setgid bit set.

File::setuid?[править]


 File.setuid?(file_name)   =>  true or false

Returns true if the named file has the setuid bit set.

File::short_path[править]


 File::short_path(file)

Returns 'file_name' in 8.3 format. For example, 'c:\documentation.doc' would be returned as 'c:\docume~1.doc'. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

File::size?, File::size, File::blksize, File::size===File::size?===


 File.file?(file_name)   => integer  or  nil

Returns nil if file_name doesn't exist or has zero size, the size of the file otherwise.

File::socket?[править]


 File.socket?(file_name)   =>  true or false

Returns true if the named file is a socket.

File::sparse?[править]


 File::sparse?(file)

Returns true if the file is a sparse file. A sparse file is a file in which much of the data is zeros, typically image files. See http://msdn.microsoft.com for more details. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

File::split, File::splitБолее одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

File::lstat, File::stat, File::lstat, File::stat===File::sticky?===


 File.sticky?(file_name)   =>  true or false

Returns true if the named file has the sticky bit set.

File::symlink[править]


 File.symlink(old_name, new_name)   => 0

Creates a symbolic link called new_name for the existing file old_name. Raises a NotImplemented exception on platforms that do not support symbolic links.

  File.symlink("testfile", "link2test")   #=> 0

File::symlink?[править]


 File.symlink?(file_name)   =>  true or false

Returns true if the named file is a symbolic link.

File::syscopy[править]


 File::syscopy(from, to)

Copies a file from to to. If to is a directory, copies from to to/from.

File::system?[править]


 File::system?(file)

Returns true if the file or directory is part of the operating system or is used exclusively by the operating system.

File::temporary?[править]


 File::temporary?(file)

Returns true if the file is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because often the application deletes the temporary file shortly after the handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data will be written after the handle is closed.

File::truncate[править]


 File.truncate(file_name, integer)  => 0

Truncates the file file_name to be at most integer bytes long. Not available on all platforms.

  f = File.new("out", "w")
  f.write("1234567890")     #=> 10
  f.close                   #=> nil
  File.truncate("out", 5)   #=> 0
  File.size("out")          #=> 5

File::umask[править]


 File.umask()          => integer
 File.umask(integer)   => integer

Returns the current umask value for this process. If the optional argument is given, set the umask to that value and return the previous value. Umask values are subtracted from the default permissions, so a umask of 0222 would make a file read-only for everyone.

  File.umask(0006)   #=> 18
  File.umask         #=> 6

File::unlink[править]


 File.delete(file_name, ...)  => integer
 File.unlink(file_name, ...)  => integer

Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error. See also Dir::rmdir.

File::utime[править]


 File.utime(atime, mtime, file_name,...)   =>  integer

Sets the access and modification times of each named file to the first two arguments. Returns the number of file names in the argument list.

File::writable?[править]


 File.writable?(file_name)   => true or false

Returns true if the named file is writable by the effective user id of this process.

File::writable_real?[править]


 File.writable_real?(file_name)   => true or false

Returns true if the named file is writable by the real user id of this process.

File::zero?[править]


 File.zero?(file_name)   => true or false

Returns true if the named file exists and has a zero size.

File#archive=[править]


 archive=(bool)

Sets whether or not the file is an archive file.

File#atime[править]


 file.atime    => time

Returns the last access time (a Time object)

for file, or epoch if file has not been accessed.
  File.new("testfile").atime   #=> Wed Dec 31 18:00:00 CST 1969

File#chmod[править]


 file.chmod(mode_int)   => 0

Changes permission bits on file to the bit pattern represented by mode_int. Actual effects are platform dependent; on Unix systems, see chmod(2) for details. Follows symbolic links. Also see File#lchmod.

  f = File.new("out", "w");
  f.chmod(0644)   #=> 0

(еще известен как o_chmod)

File#chown[править]


 file.chown(owner_int, group_int )   => 0

Changes the owner and group of file to the given numeric owner and group id's. Only a process with superuser privileges may change the owner of a file. The current owner of a file may change the file's group to any group to which the owner belongs. A nil or -1 owner or group id is ignored. Follows symbolic links. See also File#lchown.

  File.new("testfile").chown(502, 1000)

File#compressed=[править]


 compressed=(bool)

Sets whether or not the file is a compressed file.

File#content_indexed=[править]


 content_indexed=(bool)

Alias for #indexed=

File#ctime[править]


 file.ctime -> time

Returns the change time for file (that is, the time directory information about the file was changed, not the file itself).

  File.new("testfile").ctime   #=> Wed Apr 09 08:53:14 CDT 2003

File#flock[править]


 file.flock (locking_constant ) =>  0 or false

Locks or unlocks a file according to locking_constant (a logical or of the values in the table below). Returns false if File::LOCK_NB is specified and the operation would otherwise have blocked. Not available on all platforms. Locking constants (in class File):

  LOCK_EX   | Exclusive lock. Only one process may hold an
            | exclusive lock for a given file at a time.
  ----------+------------------------------------------------
  LOCK_NB   | Don't block when locking. May be combined
            | with other lock options using logical or.
  ----------+------------------------------------------------
  LOCK_SH   | Shared lock. Multiple processes may each hold a
            | shared lock for a given file at the same time.
  ----------+------------------------------------------------
  LOCK_UN   | Unlock.

Example:

  File.new("testfile").flock(File::LOCK_UN)   #=> 0

File#hidden=[править]


 hidden=(bool)

Sets the hidden attribute to true or false. Setting this attribute to true means that the file is not included in an ordinary directory listing.

File#indexed=[править]


 indexed=(bool)

Sets the 'indexed' attribute to true or false. Setting this to false means that the file will not be indexed by the content indexing service.

(еще известен как content_indexed=)

File#lstat[править]


 file.lstat   =>  stat

Same as IO#stat, but does not follow the last symbolic link. Instead, reports on the link itself.

  File.symlink("testfile", "link2test")   #=> 0
  File.stat("testfile").size              #=> 66
  f = File.new("link2test")
  f.lstat.size                            #=> 8
  f.stat.size                             #=> 66

File#mtime[править]


 file.mtime -> time

Returns the modification time for file.

  File.new("testfile").mtime   #=> Wed Apr 09 08:53:14 CDT 2003

File#normal=[править]


 normal=(bool)

Sets the normal attribute. Note that only 'true' is a valid argument, which has the effect of removing most other attributes. Attempting to pass any value except true will raise an ArgumentError.

File#o_chmod[править]


 o_chmod(p1)

Alias for #chmod

File#offline=[править]


 offline=(bool)

Sets whether or not a file is online or not. Setting this to false means that the data of the file is not immediately available. This attribute indicates that the file data has been physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not arbitrarily change this attribute.

File#path[править]


 file.path -> filename

Returns the pathname used to create file as a string. Does not normalize the name.

  File.new("testfile").path               #=> "testfile"
  File.new("/tmp/../tmp/xxx", "w").path   #=> "/tmp/../tmp/xxx"

File#readonly=[править]


 readonly=(bool)

Sets the readonly attribute. If set to true the the file or directory is readonly. Applications can read the file but cannot write to it or delete it. In the case of a directory, applications cannot delete it.

File#sparse=[править]


 sparse=(bool)

Sets the file to a sparse (usually image) file. Note that you cannot remove the sparse property from a file.

File#stat[править]


 stat()

Instance methods

File#system=[править]


 system=(bool)

Set whether or not the file is a system file. A system file is a file that is part of the operating system or is used exclusively by it.

File#temporary=[править]


 temporary=(bool)

Sets whether or not the file is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because often the application deletes the temporary file shortly after the handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data will be written after the handle is closed.

File#truncate[править]


 file.truncate(integer)    => 0

Truncates file to at most integer bytes. The file must be opened for writing. Not available on all platforms.

  f = File.new("out", "w")
  f.syswrite("1234567890")   #=> 10
  f.truncate(5)              #=> 0
  f.close()                  #=> nil
  File.size("out")           #=> 5

Класс FileTest[править]

FileTest implements file test operations similar to those used in File::Stat. It exists as a standalone module, and its methods are also insinuated into the File class. (Note that this is not done by inclusion: the interpreter cheats).


Методы объекта

blockdev?, chardev?, directory?, executable?, executable_real?, exist?, exists?, file?, grpowned?, identical?, owned?, pipe?, readable?, readable_real?, setgid?, setuid?, size?, size, socket?, sticky?, symlink?, writable?, writable_real?, zero?

FileTest#blockdev?[править]


 File.blockdev?(file_name)   =>  true or false

Returns true if the named file is a block device.

FileTest#chardev?[править]


 File.chardev?(file_name)   =>  true or false

Returns true if the named file is a character device.

FileTest#directory?[править]


 File.directory?(file_name)   =>  true or false

Returns true if the named file is a directory, false otherwise.

  File.directory?(".")

FileTest#executable?[править]


 File.executable?(file_name)   => true or false

Returns true if the named file is executable by the effective user id of this process.

FileTest#executable_real?[править]


 File.executable_real?(file_name)   => true or false

Returns true if the named file is executable by the real user id of this process.

FileTest#exist?[править]


 File.exist?(file_name)    =>  true or false
 File.exists?(file_name)   =>  true or false    (obsolete)

Return true if the named file exists.

FileTest#exists?[править]


 File.exist?(file_name)    =>  true or false
 File.exists?(file_name)   =>  true or false    (obsolete)

Return true if the named file exists.

FileTest#file?[править]


 File.file?(file_name)   => true or false

Returns true if the named file exists and is a regular file.

FileTest#grpowned?[править]


 File.grpowned?(file_name)   => true or false

Returns true if the named file exists and the effective group id of the calling process is the owner of the file. Returns false on Windows.

FileTest#identical?[править]


 File.identical?(file_1, file_2)   =>  true or false

Returns true if the named files are identical.

   open("a", "w") {}
   p File.identical?("a", "a")      #=> true
   p File.identical?("a", "./a")    #=> true
   File.link("a", "b")
   p File.identical?("a", "b")      #=> true
   File.symlink("a", "c")
   p File.identical?("a", "c")      #=> true
   open("d", "w") {}
   p File.identical?("a", "d")      #=> false

FileTest#owned?[править]


 File.owned?(file_name)   => true or false

Returns true if the named file exists and the effective used id of the calling process is the owner of the file.

FileTest#pipe?[править]


 File.pipe?(file_name)   =>  true or false

Returns true if the named file is a pipe.

FileTest#readable?[править]


 File.readable?(file_name)   => true or false

Returns true if the named file is readable by the effective user id of this process.

FileTest#readable_real?[править]


 File.readable_real?(file_name)   => true or false

Returns true if the named file is readable by the real user id of this process.

FileTest#setgid?[править]


 File.setgid?(file_name)   =>  true or false

Returns true if the named file has the setgid bit set.

FileTest#setuid?[править]


 File.setuid?(file_name)   =>  true or false

Returns true if the named file has the setuid bit set.

FileTest#size[править]


 File.size(file_name)   => integer

Returns the size of file_name.

FileTest#size?[править]


 File.file?(file_name)   => integer  or  nil

Returns nil if file_name doesn't exist or has zero size, the size of the file otherwise.

FileTest#socket?[править]


 File.socket?(file_name)   =>  true or false

Returns true if the named file is a socket.

FileTest#sticky?[править]


 File.sticky?(file_name)   =>  true or false

Returns true if the named file has the sticky bit set.

FileTest#symlink?[править]


 File.symlink?(file_name)   =>  true or false

Returns true if the named file is a symbolic link.

FileTest#writable?[править]


 File.writable?(file_name)   => true or false

Returns true if the named file is writable by the effective user id of this process.

FileTest#writable_real?[править]


 File.writable_real?(file_name)   => true or false

Returns true if the named file is writable by the real user id of this process.

FileTest#zero?[править]


 File.zero?(file_name)   => true or false

Returns true if the named file exists and has a zero size.

Класс Fixnum < Integer[править]

Класс Fixnum - это целые числа (Integer), которые умещаются в одно машинное слово (минус 1 бит). Если в результате какой либо операции число класса Fixnum выходит за пределы этого диапазона, то значение автоматически преобразуется к классу Bignum. Объекты класса Fixnum имеют непосредственное значение. Это значит, что, когда они присваиваются или передаются в качестве параметра, происходит передача фактического объекта, не не ссылки. Присваивание не работает с ссылками на объекты Fixnum. Существует лишь один объект Fixnum для каждого целочисленного значения. Именно поэтому вы не можете добавить метод-одиночку для объекта Fixnum.


Примеси

Precision (prec, prec_f, prec_i)

Константы

XChar

Методы класса

induced_from

Методы объекта

[], %, &, **, *, +, -@, -, /, <<, <=>, <=, <, ==, >=, >>, >, ^, abs, divmod, div, id2name, modulo, power!, quo, rdiv, rpower, size, to_f, to_sym, to_s, zero?, ||, ~

Fixnum::induced_from[править]


Fixnum.induced_from(obj)   #->  fixnum

Преобразует obj в объект класса Fixnum. Работает с числовыми параметрами. Еще работает с символами, но рекомендуется не использовать данную возможность.

Fixnum#%[править]


fix % other        #-> numeric
fix.modulo(other)  #-> numeric

Возвращает остаток от деления числа fix на числоother.

5 % 2      #-> 1
5 % -2     #-> -1
5 % -2.2   #-> -1.6
Информация

Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации

Информация

Методы % и modulo — абсолютно идентичны, то есть являются именами одного и того же метода

Информация

Полезно посмотреть на методы **, +, -, / и *, которые имеют схожую функциональность

Fixnum#&[править]


fix & other    #-> integer

Побитовое И.

Fixnum#*[править]


fix * numeric  #->  numeric_result

Производит умножение: результат является одним из потомков класса Numeric и зависит от величины результата.

Информация

Полезно посмотреть на методы **, +, -, / и %, которые имеют схожую функциональность

Fixnum#**[править]


fix ** other       #-> rational или numeric
fix.rpower(other)  #-> numeric или rational

Производит возведение числа fix в степень other. Возвращает рациональное число, если результат рациональный (то есть, когда other < 0).

2 ** 8    #-> 256
2 ** -8   #-> Rational(1,256)
Информация

Методы ** и rpower — абсолютно идентичны, то есть являются именами одного и того же метода

Информация

Полезно посмотреть на методы *, +, -, /, % и power!, которые имеют схожую функциональность

Fixnum#+[править]


fix + numeric  #->  numeric_result

Производит сложение: результат является одним из потомков класса Numeric и зависит от величины результата.

Информация

Полезно посмотреть на методы **, *, -, / и %, которые имеют схожую функциональность

Fixnum#-[править]


fix - numeric  #->  numeric_result

Производит вычитание: результат является одним из потомков класса Numeric и зависит от величины результата.

Информация

Полезно посмотреть на методы **, +, *, / и %, которые имеют схожую функциональность

Fixnum#-@[править]


-fix  #->  integer

Отрицание fix (может вернуть значение класса Bignum).

Fixnum#/[править]


fix / numeric     #->  numeric_result
fix.div(numeric)  #->  numeric_result

Производит целочисленное деление: результат является одним из потомков класса Numeric и зависит от величины результата.

Информация

Методы / и div — абсолютно идентичны, то есть являются именами одного и того же метода

Информация

Полезно посмотреть на методы **, +, -, * и %, которые имеют схожую функциональность

Fixnum#<[править]


fix < other    #-> true или false

Возвращает true, если значение числа fix меньше, чем значение числа other.

Fixnum#<<[править]


fix << count    #-> integer

Побитовый сдвиг числа fix влево на count позиций (вправо, если count меньше нуля).

Fixnum#<=[править]


fix <= other    #-> true или false

Возвращает true, если значение числа fix меньше или равно значению числа other.

Fixnum#<=>[править]


fix <=> numeric   #-> -1, 0, +1

Сравнение -- возвращает -1, 0 или +1, если значение числа fix меньше, равно или больше значения числа numeric, соответственно. Это базис для тестов в примеси Comparable.

Fixnum#==[править]


fix == other    #-> true или false

Возвращает true, если значение числа fix равно значению числа other.

1 == 2      #-> false
1 == 1.0    #-> true

Fixnum#>[править]


fix > other    #-> true или false

Возвращает true, если значение числа fix больше, чем значение числа other.

Fixnum#>=[править]


fix >= other    #-> true или false

Возвращает true, если значение числа fix больше или равно, чем значение числа other.

Fixnum#>>[править]


fix >> count    #-> integer

Побитовый сдвиг числа fix вправо на count позиций (влево, если count меньше нуля).

Fixnum#[][править]


fix[n]    #-> 0, 1

Побитовый доступ -- возвращает nый бит двоичного представления числа fix, где fix[0] -- младший significant бит.

a = 0b11001100101010
30.downto(0) do |n| print a[n] end

результат:

 0000000000000000011001100101010

Fixnum#^[править]


fix ^ other    #-> integer

Побитовое ИСКЛЮЧАЮЩЕЕ ИЛИ.

Fixnum#abs[править]


fix.abs   #-> fixnum

Возвращает абсолютное значение числа fix.

-12345.abs   #-> 12345
12345.abs    #-> 12345

Fixnum#div[править]


fix / numeric     #->  numeric_result
fix.div(numeric)  #->  numeric_result

Производит целочисленное деление: результат является одним из потомков класса Numeric и зависит от величины результата.

Информация

Методы / и div — абсолютно идентичны, то есть являются именами одного и того же метода

Fixnum#divmod[править]


fix.divmod(numeric)   #-> array

Информация

Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации

Fixnum#id2name[править]


fix.id2name    #-> string или nil

Возвращает имя объекта с id равным fix. Возвращает nil, если в символьной таблице не найдено ни одного символа, соответствующего значению fix.

symbol = :@inst_var    #-> :@inst_var
id     = symbol.to_i   #-> 9818
id.id2name             #-> "@inst_var"
Информация
  • Для более полного представления о работе данного метода советуем взглянуть на описания методов to_sym, String#intern и описание класса Symbol
  • Метод id2name никак не взаимодействует с методом Object#id

Fixnum#modulo[править]


fix % other        #-> Numeric
fix.modulo(other)  #-> Numeric

Возвращает остаток от деления числа fix на числоother.

Информация

Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации

Информация

Методы % и modulo — абсолютно идентичны, то есть являются именами одного и того же метода

Fixnum#power![править]


fix.power!( other )  #-> numeric

Производит возведение числа fix в степень other.

2.power!( 8 )    #-> 256
2.power( -8 )   #-> 0.00390625
Информация

Полезно посмотреть на методы ** и rpower, которые имеют схожую функциональность

Fixnum#quo[править]


fix.quo(numeric)   #-> float
fix.rdiv(numeric)  #-> float

Возвращает дробный результат деления числа fix на число numeric.

654321.quo(13731)      #-> 47.6528293642124
654321.quo(13731.24)   #-> 47.6519964693647
Информация

Методы quo и rdiv — абсолютно идентичны, то есть являются именами одного и того же метода

Fixnum#rdiv[править]


fix.quo(numeric)   #-> float
fix.rdiv(numeric)  #-> float

Возвращает дробный результат деления числа fix на число numeric.

654321.rdiv(13731)      #-> 47.6528293642124
654321.rdiv(13731.24)   #-> 47.6519964693647
Информация

Методы quo и rdiv — абсолютно идентичны, то есть являются именами одного и того же метода

Fixnum#rpower[править]


fix ** other       #-> rational или numeric
fix.rpower(other)  #-> rational или numeric

Производит возведение числа fix в степень other. Возвращает рациональное число, если результат рациональный (то есть, когда other < 0).

2.rpower( 8 )    #-> 256
2.rpower( -8 )   #-> Rational(1,256)
Информация

Методы ** и rpower — абсолютно идентичны, то есть являются именами одного и того же метода

Информация

Полезно посмотреть на метод power!, который имеет схожую функциональность

Fixnum#size[править]


fix.size   #-> fixnum

Возвращает количество байт машинного представления числа fix.

1.size            #-> 4
-1.size           #-> 4
2147483647.size   #-> 4

Fixnum#to_f[править]


fix.to_f   #-> float

Преобразует значение числа fix к классу Float.

Информация

Полезно посмотреть на методы to_s и to_sym, которые имеют схожую функциональность

Fixnum#to_s[править]


fix.to_s( base=10 )   #-> string

Возвращает строку, где число fix имеет основание системы счисления равное base (между 2 и 36). По умолчанию base=10 (то есть десятичная система счисления).

12345.to_s       #-> "12345"
12345.to_s(2)    #-> "11000000111001"
12345.to_s(8)    #-> "30071"
12345.to_s(10)   #-> "12345"
12345.to_s(16)   #-> "3039"
12345.to_s(36)   #-> "9ix"
Информация

Полезно посмотреть на методы to_f и to_sym, которые имеют схожую функциональность

Fixnum#to_sym[править]


fix.to_sym   #-> symbol

Возвращает символ, которому соответствует значение fix.

fred = :fred.to_i
fred.id2name   #-> "fred"
fred.to_sym    #-> :fred
Информация

Полезно посмотреть на методы to_s, to_f и id2name, которые имеют схожую функциональность


Fixnum#zero?[править]


fix.zero?   #-> true или false

Возвращает true, если значение fix равно нулю.

Fixnum#|[править]


fix | other    #-> integer

Побитовое ИЛИ.

Fixnum#~[править]


~fix    #-> integer

Побитовое НЕ.

Класс Float < Numeric[править]

Объекты класса Float представляют собой вещественные числа, то есть дробные числа с плавающей точкой двойной точности (аналог типа double в языке Си).


Примеси

Precision (prec, prec_f, prec_i)

Константы

DIG, EPSILON, MANT_DIG, MAX, MAX_10_EXP, MAX_EXP, MIN, MIN_10_EXP, MIN_EXP, RADIX, ROUNDS

Методы класса

induced_from

Методы объекта

%, **, *, +, -@, -, /, <->, <=, <, ==, >=, >, abs, ceil, coerce, divmod, eql?, finite?, floor, hash, infinite?, modulo, nan?, round, to_f, to_int, to_i, to_s, truncate, zero?

Float::induced_from[править]


Float.induced_from(obj)    #->  float

Преобразует obj в вещественное число.

Float#%[править]


flt % other         #-> float
flt.modulo(other)   #-> float

Возвращает остаток от деления числа flt на число other.

6543.21 % 137      #-> 104.21
6543.21 % 137.24   #-> 92.9299999999996
Информация

Методы % и modulo — абсолютно идентичны, то есть являются именами одного и того же метода

Float#*[править]


flt * other   #-> float

Возвращает вещественное число, которое является результатом произведения flt на other.

Информация

Полезно посмотреть на методы **, +, -, / и %, которые имеют схожую функциональность

Float#**[править]


flt ** other   #-> float

Возвращает вещественное число, которое является результатом возведения числа flt в степень other.

Информация

Полезно посмотреть на методы *, +, -, / и %, которые имеют схожую функциональность

Float#+[править]


flt + other   #-> float

Возвращает вещественное число, которое является суммой чисел flt и other.

Информация

Полезно посмотреть на методы **, *, -, / и %, которые имеют схожую функциональность

Float#-[править]


flt - other   #-> float

Возвращает вещественное число, которое является разностью чисел flt и other.

Информация

Полезно посмотреть на методы **, +, *, / и %, которые имеют схожую функциональность

Float#-@[править]


-flt   #-> float

Возвращает вещественное число, обратное по знаку (по отношению к flt).

Float#/[править]


float / other   #-> float

Возвращает вещественное число, которое является частным чисел flt и other.

Информация

Полезно посмотреть на методы **, +, -, * и %, которые имеют схожую функциональность

Float#<[править]


flt < other    #->  true или false

Возвращает true, если число flt меньше, чем число other.

Float#<=[править]


flt <= other    #->  true or false

Возвращает true, если число flt меньше или равно по отношению к числу other.

Float#<=>[править]


flt <=> numeric   #-> -1, 0, +1

Возвращает -1, 0 или +1, когда число flt меньше, равно или больше числа numeric, соответственно. Этот метод необходим для нормальной работы примеси Comparable.

Float#==[править]


flt == obj   #-> true или false

Возвращает true только если число obj имеет точно такое же значение, как и число flt. В отличие от метода eql?, преобразует obj в вещественное число.

1.0 == 1   #-> true

Float#>[править]


flt > other    #->  true или false

Возвращает true, если число flt больше, чем число other.

Float#>=[править]


flt >= other    #->  true или false

Возвращает true, если число flt больше или равно по отношению к числу other.

Float#abs[править]


flt.abs    #-> float

Возвращает абсолютную величину числа flt.

(-34.56).abs   #-> 34.56
-34.56.abs     #-> 34.56

Float#ceil[править]


flt.ceil    #-> integer

Возвращает наименьшее целое число большее или равное числу flt.

1.2.ceil      #-> 2
2.0.ceil      #-> 2
(-1.2).ceil   #-> -1
(-2.0).ceil   #-> -2
Информация

Полезно посмотреть на методы floor, round и truncate, которые имеют схожую функциональность

Float#coerce[править]


flt.coerce(other)    #-> array

Возвращает массив, состоящий из чисел other и flt, которые преобразованы к вещественному типу. Этот метод используется при обработке арифметических операций со смешанными типами.

1.2.coerce(3)   #-> [3.0, 1.2]
1.0.coerce(2.0)     #-> [2.0, 1.0]

Float#divmod[править]


flt.divmod(numeric)    #-> array

См. описание метода Numeric#divmod.

Float#eql?[править]


flt.eql?(obj)   #-> true или false

Возвращает true, если obj является вещественным числом и имеет значение равное flt. В отличие от метода ==, преобразований типов не производится.

1.0.eql?(1)   #-> false

Float#finite?[править]


flt.finite?   #-> true или false

Возвращает true, если flt является правильным вещественным числом по стандартам IEEE (то есть не является бесконечностью и метод nan? возвращает false).

Float#floor[править]


flt.floor    #-> integer

Возвращает наибольшее целое, меньшее или равное flt.

1.2.floor      #-> 1
2.0.floor      #-> 2
(-1.2).floor   #-> -2
(-2.0).floor   #-> -2
Информация

Полезно посмотреть на методы ceil, round и truncate, которые имеют схожую функциональность

Float#hash[править]


flt.hash    #-> integer

Возвращает хеш-код вещественного числа flt.

Float#infinite?[править]


flt.infinite?   #-> nil, -1, +1

Возвращает nil, -1 или +1, если вещественное число flt конечно, устремлено в или в , соответственно.

(0.0).infinite?        #-> nil
(-1.0/0.0).infinite?   #-> -1
(+1.0/0.0).infinite?   #-> 1

Float#modulo[править]


flt % other         #-> float
flt.modulo(other)   #-> float

Возвращает остаток от деления числа flt на число other.

6543.21.modulo(137)      #-> 104.21
6543.21.modulo(137.24)   #-> 92.9299999999996

Float#nan?[править]


flt.nan? -> true или false

Возвращает true, если число flt не удовлетворяет стандарту IEEE на вещественные числа.

a = -1.0      #-> -1.0
a.nan?        #-> false
a = 0.0/0.0   #-> NaN
a.nan?        #-> true

Float#round[править]


flt.round   #-> integer

Возвращает ближайшее целое число к вещественному числу flt. Метод эквивалентен следующей записи:

def round
  return floor(self+0.5) if self > 0.0
  return ceil(self-0.5)  if self < 0.0
  return 0.0
end

1.5.round      #-> 2
(-1.5).round   #-> -2
Информация

Полезно посмотреть на методы floor, ceil и truncate, которые имеют схожую функциональность

Float#to_f[править]


flt.to_f   #-> flt

Так как flt уже является вещественным числом, то данный метод всегда возвращает ftl.

Float#to_i[править]


flt.to_i       #-> integer
flt.to_int     #-> integer
flt.truncate   #-> integer

Возвращает целое число, которое является целой частью вещественного числа flt.

Информация

Методы to_i, to_int и truncate — абсолютно идентичны, то есть являются именами одного и того же метода

Float#to_int[править]


flt.to_i       #-> integer
  flt.to_int     #-> integer
 flt.truncate   #-> integer

Возвращает целое число, которое является целой частью вещественного числа flt.

Информация

Методы to_i, to_int и truncate — абсолютно идентичны, то есть являются именами одного и того же метода

Float#to_s[править]


flt.to_s    #-> string

Возвращает строку, которая содержит строковое представление вещественного числа flt. Число flt может быть представлено как в обычной, так и в экспоненциальной форме записи, а также иметь значения NaN, Infinity, -Infinity.

Float#truncate[править]


flt.to_i       #-> integer
  flt.to_int     #-> integer
  flt.truncate   #-> integer

Возвращает целое число, которое является целой частью вещественного числа flt.

Информация

Полезно посмотреть на методы floor, round и ceil, которые имеют схожую функциональность

Информация

Методы to_i, to_int и truncate — абсолютно идентичны, то есть являются именами одного и того же метода

Float#zero?[править]


flt.zero? -> true или false

Возвращает true, если вещественное число flt является числом 0.0.

Класс GC[править]

Модуль GC обеспечивает Руби-интерфейс, который позволяет управлять механизмом сборки мусора. Некоторые из методов также доступны через модуль ObjectSpace.


Методы класса

disable, enable, start

Методы объекта

garbage_collect

GC::disable[править]


GC.disable    #-> true или false

Отключает сборку мусора, возвращает true если сборка мусора уже была отключена.

GC.disable   #-> false
GC.disable   #-> true

GC::enable[править]


GC.enable    #-> true или false

Включает сборку мусора, возвращает true если сборка мусора была предварительно отключена.

GC.disable   #-> false
GC.enable    #-> true
GC.enable    #-> false

GC::start[править]


GC.start                     #-> nil
gc.garbage_collect           #-> nil
ObjectSpace.garbage_collect  #-> nil

Начинает сборку мусора, пока не отключена вручную.

GC#garbage_collect[править]


GC.start                     #-> nil
gc.garbage_collect           #-> nil
ObjectSpace.garbage_collect  #-> nil

Начинает сборку мусора, пока не отключена вручную.

Класс Hash[править]

Хеш - коллекция пар ключ-значение. Хеш подобен классу Array, за исключением того, что индексация осуществляется через ключи (объекты любого типа), а не через целочисленные индексы. Последовательность перечисления пар ключ-значений хеша может оказаться произвольной, и обычно не совпадает с той, в которой вы заполняли хеш. При обращении к хешу по ключу, которого не существует, возвращается значение по-умолчанию. Изначально, этим значением является nil.


Примеси

Enumerable (all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find, find_all, grep, group_by, include?, index_by, inject, map, max, member?, min, partition, reject, select, sort, sort_by, sum, to_a, to_set, zip)

Методы класса

[], new

Методы объекта

[]=, [], ==, clear, default=, default_proc, default, delete_if, delete, each_key, each_pair, each_value, each, empty?, fetch, has_key?, has_value?, include?, indexes, index, indices, inspect, invert, key?, keys, length, member?, merge!, merge, rehash, reject!, reject, replace, select, shift, size, sort, store, to_a, to_hash, to_s, update, value?, values_at, values

Hash::[][править]


Hash [key =>|, value]* ]   #-> hash

Создает новый хеш, заполненный заданными объектами. Эквивалентно литералу { key, value, ... }.

Hash["a", 100, "b", 200]       #-> {"a"=>100, "b"=>200}
Hash["a" => 100, "b" => 200]   #-> {"a"=>100, "b"=>200}
{ "a" => 100, "b" => 200 }     #-> {"a"=>100, "b"=>200}

Hash::new[править]


Hash.new                          #-> hash
Hash.new(obj)                     #-> aHash
Hash.new {|hash, key| block }     #-> aHash

Возвращает новый хеш. При последующем обращении к хешу по ключу, которого не существует в этом хеше, возвращаемое значение зависит от формы вызова метода new. В первой форме вызова вернется значение nil. Если указан объект obj, то этот единственный объект будет использоваться для всех значений по-умолчанию. Если указан блок, тогда значение по-умолчанию вычисляется в данном блоке, которому передаются хеш (текущий) и ключ. В блоке можно записать значение в хеш, если это необходимо.

h = Hash.new("Go Fish")
h["a"] = 100
h["b"] = 200
h["a"]           #-> 100
h["c"]           #-> "Go Fish"
# Изменяется единственный объект по-умолчанию
h["c"].upcase!   #-> "GO FISH"
h["d"]           #-> "GO FISH"
h.keys           #-> ["a", "b"]

# Создается новый объект по умолчанию каждый раз
h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
h["c"]           #-> "Go Fish: c"
h["c"].upcase!   #-> "GO FISH: C"
h["d"]           #-> "Go Fish: d"
h.keys           #-> ["c", "d"]

Hash#==[править]


hsh == other_hash    #-> true или false

Равенство — два хеша считаются равными, если они содержат одинаковое число ключей, и если каждая пара ключ-значение эквивалентна (согласно методу Object#==) соответствующим элементам в другом хеше.

h1 = { "a" => 1, "c" => 2 }
h2 = { 7 => 35, "c" => 2, "a" => 1 }
h3 = { "a" => 1, "c" => 2, 7 => 35 }
h4 = { "a" => 1, "d" => 2, "f" => 35 }
h1 == h2   #-> false
h2 == h3   #-> true
h3 == h4   #-> false

Hash#[][править]


hash[key]    #->  value

Получение элемента — возвращает значение соответствующее ключу key. Если ключа не существует, то возвращается значение по-умолчанию (см. Hash::new).

h = { "a" => 100, "b" => 200 }
h["a"]   #-> 100
h["c"]   #-> nil

Hash#[]=[править]


hsh[key] = value        #-> value

Присваивание - ассоциирует значение value с ключем key.

h = { "a" => 100, "b" => 200 }
h["a"] = 9
h["c"] = 4
h   #-> {"a"=>9, "b"=>200, "c"=>4}
Информация

Данный метод и метод store — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#clear[править]


hsh.clear #-> hsh

Удаляет все пары ключ-значение из хеша hsh.

h = { "a" => 100, "b" => 200 }   #-> {"a"=>100, "b"=>200}
h.clear                          #-> {}

Hash#default[править]


hsh.default(key=nil)   #-> obj

Возвращает значение по-умолчанию, т.е. значение, которое будет возвращать hsh[key], если ключа key не существует в хеше hsh.

h = Hash.new                            #-> {}
h.default                               #-> nil
h.default(2)                            #-> nil

h = Hash.new("cat")                     #-> {}
h.default                               #-> "cat"
h.default(2)                            #-> "cat"

h = Hash.new {|h,k| h[k] = k.to_i*10}   #-> {}
h.default                               #-> 0
h.default(2)                            #-> 20
Информация

Полезно взглянуть также на методы Hash::new и Hash#default=

Hash#default=[править]


hsh.default = obj     #-> hsh

Устанавливает значение по-умолчанию, т.е. значение, которое возвращает hsh[key], если ключа key не существует в хеше hsh.

h = { "a" => 100, "b" => 200 }
h.default = "Go fish"
h["a"]     #-> 100
h["z"]     #-> "Go fish"

# Это не сделает того, на что вы надеятесь...
h.default = proc do |hash, key|
   hash[key] = key + key
end
h[2]       #-> #<Proc:0x401b3948@-:6>
h["cat"]   #-> #<Proc:0x401b3948@-:6>

Hash#default_proc[править]


hsh.default_proc  #-> anObject

Если метод Hash::new был вызван с блоком, то возвращает блок, иначе возвращает nil.

h = Hash.new {|h,k| h[k] = k*k }   #-> {}
p = h.default_proc                 #-> #<Proc:0x401b3d08@-:1>
a = []                             #-> []
p.call(a, 2)
a                                  #-> [nil, nil, 4]

Hash#delete[править]


hsh.delete(key)                   #-> value
hsh.delete(key) {| key | block }  #-> value

Удаляет пару ключ-значение из хеша hsh, которая соответствует ключу key. Возвращается значение, соответствующее ключу. Если ключ не был найден, тогда возвращается "значение по-умолчанию". Если используется конструкция с блоком и ключ не был найден, то возвращается результат выполнения блока block, которому передается ключ key.

h = { "a" => 100, "b" => 200 }
h.delete("a")                              #-> 100
h.delete("z")                              #-> nil
h.delete("z") { |el| "#{el} не найден" }   #-> "z не найден"

Hash#delete_if[править]


hsh.delete_if {| key, value | block }  #-> hsh

Удаляет все пары ключ-значение из хеша hsh для которых блок block вычисляет значение true.

h = { "a" => 100, "b" => 200, "c" => 300 }
h.delete_if {|key, value| key >= "b" }   #-> {"a"=>100}

Hash#each[править]


hsh.each {| key, value | block }   #-> hsh

Вызывает блок для каждый пары ключ-значение хеша hsh и передает в блок текущую пару ключ-значение в виде массива из двух элементов. В виду семантических особенностей параметров блока, эти параметры могут быть представлены не массивом, а двумя элементами с различными именами. Еще существует метод each_pair, который чуть более эффективен для блоков с двумя параметрами.

h = { "a" => 100, "b" => 200 }
h.each {|key, value| puts "#{key} => #{value}" }

результат:

 a => 100
 b => 200

Hash#each_key[править]


hsh.each_key {| key | block } #-> hsh

Выполняет блок block для каждого ключа в хеше hsh, передавая в блок ключ key в качестве параметра.

h = { "a" => 100, "b" => 200 }
h.each_key {|key| puts key }

результат:

a
b

Hash#each_pair[править]


hsh.each_pair {| key_value_array | block } #-> hsh

Выполняет блок block для каждого ключа в хеше hsh, передавая в блок ключ и значение в качестве параметров.

h = { "a" => 100, "b" => 200 }
h.each_pair {|key, value| puts "#{key} => #{value}" }

результат:

a => 100
b => 200

Hash#each_value[править]


hsh.each_value {| value | block } #-> hsh

Выполняет блок block для каждого ключа в хеше hsh, передавая в блок значение value, соответствующее ключу, в качестве параметра.

h = { "a" => 100, "b" => 200 }
h.each_value {|value| puts value }

результат:

100
200

Hash#empty?[править]


hsh.empty?    #-> true или false

Возвращает true, если хеш hsh не содержит пар ключ-значение вовсе.

{}.empty?   #-> true

Hash#fetch[править]


hsh.fetch(key [, default] )       #-> obj
hsh.fetch(key) {| key | block }   #-> obj

Возвращает значение, соответствующее ключу key. Если ключ не был найден, тогда есть несколько ситуаций: Без иных аргументов будет подниматься исключение IndexError; Если задан параметр default, тогда он и будет возвращен; Если конструкция определена с блоком, тогда будет выполняться блок, которому в качестве аргумента будет передан ключ.

h = { "a" => 100, "b" => 200 }
h.fetch("a")                            #-> 100
h.fetch("z", "go fish")                 #-> "go fish"
h.fetch("z") { |el| "go fish, #{el}"}   #-> "go fish, z"

Следующий пример показывает, что если ключ не найден и значение по-умолчанию не поставляется, то поднимается исключение.

h = { "a" => 100, "b" => 200 }
h.fetch("z")

результат:

prog.rb:2:in `fetch': key not found (IndexError)
 from prog.rb:2

Hash#has_key?[править]


hsh.has_key?(key)    #-> true или false

Возвращает true, если заданный ключ находится в хеше hsh.

h = { "a" => 100, "b" => 200 }
h.has_key?("a")   #-> true
h.has_key?("z")   #-> false
Информация

Методы has_key?, include?, key? и member? — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#has_value?[править]


hsh.has_value?(value)    #-> true или false

Возвращает true, если заданное значение принадлежит некоторому ключу в хеше hsh.

h = { "a" => 100, "b" => 200 }
h.has_value?(100)   #-> true
h.has_value?(999)   #-> false
Информация

Методы has_value? и value? — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#include?[править]


hsh.include?(key)    #-> true или false

Возвращает true, если заданный ключ находится в хеше hsh.

h = { "a" => 100, "b" => 200 }
h.include?("a")   #-> true
h.include?("z")   #-> false
Информация

Методы include?, has_key?, key? и member? — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#index[править]


hsh.index(value)    #-> key

Возвращает ключ для заданного значения. Если значение не найдено, возвращает nil.

h = { "a" => 100, "b" => 200 }
h.index(200)   #-> "b"
h.index(999)   #-> nil

Hash#indexes[править]


hsh.indexes(key, ...)    #-> array

Информация

Методы indexes и indices — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#indices[править]


hsh.indices(key, ...)    #-> array

Информация

Методы indices и indexes — абсолютно идентичны, то есть являются именами одного и того же метода


Hash#inspect[править]


hsh.inspect  #-> string

Возвращает содержимое хеша в виде строки.

Hash#invert[править]


hsh.invert #-> aHash

Возвращает новый хеш, созданный путем использования значений хеша hsh в качестве ключей, а ключей в качестве значений.

h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
h.invert   #-> {0=>"a", 100=>"n", 200=>"d", 300=>"y"}

Hash#key[править]


hsh.key(value)    #-> key

Возвращает ключ для заданного значения. Если значение не найдено, возвращает nil.

h = { "a" => 100, "b" => 200 }
h.key(200)   #-> "b"
h.key(999)   #-> nil
Информация

Методы index и key — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#key?[править]


hsh.key?(key)    #-> true или false

Возвращает true, если заданный ключ находится в хеше hsh.

h = { "a" => 100, "b" => 200 }
h.key?("a")   #-> true
h.key?("z")   #-> false
Информация

Методы key?, has_key?, include? и member? — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#keys[править]


hsh.keys    #-> array

Возвращает новый массив, состоящий из ключей данного хеша.

h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }
h.keys   #-> ["a", "b", "c", "d"]
Информация

Полезно посмотреть на метод values, который имеет схожую функциональность

Hash#length[править]


hsh.length    #->  fixnum

Возвращает количество пар ключ-значение в данном хеше.

h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
h.length        #-> 4
h.delete("a")   #-> 200
h.length        #-> 3
Информация

Методы length и size — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#member?[править]


hsh.member?(key)    #-> true или false

Возвращает true, если заданный ключ находится в хеше hsh.

h = { "a" => 100, "b" => 200 }
h.member?("a")   #-> true
h.member?("z")   #-> false
Информация

Методы member?, has_key?, include? и key? — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#merge[править]


hsh.merge(other_hash)                                #-> a_hash
hsh.merge(other_hash){|key, oldval, newval| block}   #-> a_hash

Возвращает новый хеш, который состоит из содержимого хешей other_hash и hsh. Если в результате слияния обнаружатся одинаковые ключи, то для него будет записано значение из хеша other_hash (если задан блок, то будет записано значение, которое получится в результате выполнения блока).

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
h1             #=> {"a"=>100, "b"=>200}

Hash#merge![править]


hsh.merge!(other_hash)                                 #-> hsh
hsh.update(other_hash)                                 #-> hsh
hsh.merge!(other_hash){|key, oldval, newval| block}    #-> hsh
hsh.update(other_hash){|key, oldval, newval| block}    #-> hsh

Добавляет содержимое хеша other_hash к хешу hsh. Если обнаружатся дублирующие ключи, то значение для него будет взято из other_hash (или получено в результате выполнения блока, если он задан).

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge!(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
Информация

Методы merge! и update — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#rehash[править]


hsh.rehash   #-> hsh

Если ключами хеша являются переменные, то может возникнуть ситуация, когда их значение меняется. Чтобы иметь доступ к ассоциированным с ними данным нужно вызвать данный метод, чтобы он привел ключи в соответствие с новым значеним переменных. Если метод вызывается, в то время как итератор обходит этот самый хеш, то будет возбуждена ошибка вида IndexError.

a = [ "a", "b" ]
c = [ "c", "d" ]
h = { a => 100, c => 300 }
h[a]       #-> 100
a[0] = "z"
h[a]       #-> nil
h.rehash   #-> {["z", "b"]=>100, ["c", "d"]=>300}
h[a]       #-> 100

Hash#reject[править]


hsh.reject {| key, value | block }  #-> a_hash

То же самое, что и метод delete_if, но обрабатывает (и возвращает) копию хеша hsh. По сути, данный метод эквивалентен hsh.dup.delete_if.

Hash#reject![править]


hsh.reject! {| key, value | block }  #-> hsh или nil

Эквивалентно delete_if, но возвращает nil, если хеш не был изменен в результате работы данного метода.

Hash#replace[править]


hsh.replace(other_hash) #-> hsh

Заменяет содержимое хеша hsh на содержимое хеша other_hash.

h = { "a" => 100, "b" => 200 }
h.replace({ "c" => 300, "d" => 400 })   #-> {"c"=>300, "d"=>400}

Hash#select[править]


hsh.select {|key, value| block}   #-> hash

Возвращает новый хэш, состоящий из элементов, для которых блок вычисляет значение true.

h = { "a" => 100, "b" => 200, "c" => 300 }
h.select {|k,v| v > 100}  #-> {"b" => 200, "c" => 300}
h.select {|k,v| v < 200}  #-> {"a" => 100}

А вот так выбираем только гласные:

hash_1 = {a: 1, e: 5, i: 9, o: 15, u: 21, y: 25, b: 2, c: 3, d: 4, f: 6, g: 7, h: 8, j: 10, k: 11, l: 12, m: 13, n: 14, p: 16, q: 17, r: 18, s: 19, t: 20, v: 22, w: 23, x: 24, z: 26}

hash_2 = hash_1.select! { |k, v| [:a, :e, :i, :o, :u, :y].include?(k) }

p hash_2

На выходе {:a=>1, :e=>5, :i=>9, :o=>15, :u=>21, :y=>25}

Осторожно с ! после select ...

Hash#shift[править]


hsh.shift #-> anArray или obj

Удаляет первую пару ключ-значение из хеша hsh и возвращает эту пару в виде массива [ key, value ]. Если хеш пуст, то возвращает значение по-умолчанию.

h = { 1 => "a", 2 => "b", 3 => "c" }
h.shift   #-> [1, "a"]
h         #-> {2=>"b", 3=>"c"}

Hash#size[править]


hsh.size    #->  fixnum

Возвращает количество пар ключ-значение в данном хеше.

h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
h.size          #-> 4
h.delete("a")   #-> 200
h.size          #-> 3
Информация

Методы size и length — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#sort[править]


hsh.sort                    #-> array 
hsh.sort {| a, b | block }  #-> array

Преобразует хеш hsh в массив массивов - [ key, value ] и сортирует его, используя Array#sort.

h = { "a" => 20, "b" => 30, "c" => 10  }
h.sort                       #-> [["a", 20], ["b", 30], ["c", 10]]
h.sort {|a,b| a[1]<=>b[1]}   #-> [["c", 10], ["a", 20], ["b", 30]]

Hash#store[править]


hsh.store(key, value)   #-> value

Присваивание - ассоциирует значение value с ключем key. Идентичен методу []=.

h = { "a" => 100, "b" => 200 }
h.store("a", 9)
h.store("c", 4)
h   #-> {"a"=>9, "b"=>200, "c"=>4}

Hash#to_a[править]


hsh.to_a #-> array

Конвертирует хеш hsh в массив, состоящий из массивов [ key, value ].

h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300  }
h.to_a   #-> [["a", 100], ["c", 300], ["d", 400]]

Hash#to_hash[править]


hsh.to_hash   #-> hsh

Возвращает hsh.

Hash#to_s[править]


hsh.to_s   #-> string

Преобразует хеш hsh в строку путем преобразования хеша в массив массивов [ key, value ], и преобразования этого массива в строку, используя Array#join со стандартным разделителем.

h = { "c" => 300, "a" => 100, "d" => 400 }
h.to_s   #-> "a100c300d400"

Hash#update[править]


hsh.merge!(other_hash)                                 #-> hsh
hsh.update(other_hash)                                 #-> hsh
hsh.merge!(other_hash){|key, oldval, newval| block}    #-> hsh
hsh.update(other_hash){|key, oldval, newval| block}    #-> hsh

Добавляет содержимое хеша other_hash к хешу hsh. Если обнаружатся дублирующие ключи, то значение для него будет взято из other_hash (или получено в результате выполнения блока, если он задан).

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.update(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
Информация

Методы merge! и update — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#value?[править]


hsh.value?(value)    #-> true или false

Возвращает true, если заданное значение принадлежит некоторому ключу в хеше hsh.

h = { "a" => 100, "b" => 200 }
h.value?(100)   #-> true
h.value?(999)   #-> false
Информация

Методы value? и has_value? — абсолютно идентичны, то есть являются именами одного и того же метода

Hash#values[править]


hsh.values    #-> array

Возвращает новый массив, состоящий из значений данного хеша.

h = { "a" => 100, "b" => 200, "c" => 300 }
h.values   #=> [100, 200, 300]
Информация

Полезно посмотреть на метод keys, который имеет схожую функциональность

Hash#values_at[править]


hsh.values_at(key, ...)   #-> array

Возвращает массив содержащий значения, соответствующие заданным ключам. (См. Hash.select).

h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
h.values_at("cow", "cat")  #-> ["bovine", "feline"]

Класс IO[править]

Class IO Является базовым для ввода и вывода в Ruby. An I/O stream may be duplexed (that is, bidirectional), and so may use more than one native operating system stream. Many of the examples in this section use class File, the only standard subclass of IO. The two classes are closely associated. As used in this section, portname may take any of the following forms.

  • A plain string represents a filename suitable for the underlying operating system.
  • A string starting with ``| indicates a subprocess. The remainder of the string following the ``| is invoked as a process with appropriate input/output channels connected to it.
  • A string equal to ``|- will create another Ruby instance as a subprocess.

Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename ``/gumby/ruby/test.rb will be opened as ``\gumby\ruby\test.rb. When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:

  "c:\gumby\ruby\test.rb"

Our examples here will use the Unix-style forward slashes; File::SEPARATOR can be used to get the platform-specific separator character. I/O ports may be opened in any one of several different modes, which are shown in this section as mode. The mode may either be a Fixnum or a String. If numeric, it should be one of the operating system specific constants (O_RDONLY, O_WRONLY, O_RDWR, O_APPEND and so on). See man open(2) for more information. If the mode is given as a String, it must be one of the values listed in the following table.

 Mode |  Meaning
 -----+--------------------------------------------------------
 "r"  |  Read-only, starts at beginning of file  (default mode).
 -----+--------------------------------------------------------
 "r+" |  Read-write, starts at beginning of file.
 -----+--------------------------------------------------------
 "w"  |  Write-only, truncates existing file
      |  to zero length or creates a new file for writing.
 -----+--------------------------------------------------------
 "w+" |  Read-write, truncates existing file to zero length
      |  or creates a new file for reading and writing.
 -----+--------------------------------------------------------
 "a"  |  Write-only, starts at end of file if file exists,
      |  otherwise creates a new file for writing.
 -----+--------------------------------------------------------
 "a+" |  Read-write, starts at end of file if file exists,
      |  otherwise creates a new file for reading and
      |  writing.
 -----+--------------------------------------------------------
  "b" |  (DOS/Windows only) Binary file mode (may appear with
      |  any of the key letters listed above).

The global constant ARGF (also accessible as $<) provides an IO-like stream which allows access to all files mentioned on the command line (or STDIN if no files are mentioned). ARGF provides the methods #path and #filename to access the name of the file currently being read.


Примеси


Enumerable (all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find, find_all, grep, group_by, include?, index_by, inject, map, max, member?, min, partition, reject, select, sort, sort_by, sum, to_a, to_set, zip),

File::Constants ()

Константы

SEEK_CUR, SEEK_END, SEEK_SET

Методы класса

for_fd, foreach, new, new, open, pipe, popen, readlines, read, select, sysopen

Методы объекта

<<, binmode, block_scanf, close_read, close_write, closed?, close, each_byte, each_line, each, eof?, eof, fcntl, fileno, flush, fsync, getc, gets, inspect, ioctl, isatty, lineno=, lineno, pid, pos=, pos, printf, print, putc, puts, read_nonblock, readbytes, readchar, readlines, readline, readpartial, read, reopen, rewind, scanf, seek, soak_up_spaces, stat, sync=, sync, sysread, sysseek, syswrite, tell, to_io, to_i, tty?, ungetc, write_nonblock, write

IO::for_fd[править]


 IO.for_fd(fd, mode)    => io

Synonym for IO::new.

IO::foreach[править]


 IO.foreach(name, sep_string=$/) {|line| block }   => nil

Executes the block for every line in the named I/O port, where lines are separated by sep_string.

  IO.foreach("testfile") {|x| print "GOT ", x }

produces:

  GOT This is line one
  GOT This is line two
  GOT This is line three
  GOT And so on...

IO::new[править]


 IO.new(fd, mode_string)   => io

Returns a new IO object (a stream) for the given integer file descriptor and mode string. See also IO#fileno and IO::for_fd.

  a = IO.new(2,"w")      # '2' is standard error
  $stderr.puts "Hello"
  a.puts "World"

produces:

  Hello
  World

IO::new[править]


 IO.new(fd, mode_string)   => io

Returns a new IO object (a stream) for the given integer file descriptor and mode string. See also IO#fileno and IO::for_fd.

  a = IO.new(2,"w")      # '2' is standard error
  $stderr.puts "Hello"
  a.puts "World"

produces:

  Hello
  World

IO::open[править]


 IO.open(fd, mode_string="r" )               => io
 IO.open(fd, mode_string="r" ) {|io| block } => obj

With no associated block, open is a synonym for IO::new. If the optional code block is given, it will be passed io as an argument, and the IO object will automatically be closed when the block terminates. In this instance, IO::open returns the value of the block.

IO::pipe[править]


 IO.pipe -> array

Creates a pair of pipe endpoints (connected to each other) and returns them as a two-element array of IO objects: [ read_file, write_file ]. Not available on all platforms. In the example below, the two processes close the ends of the pipe that they are not using. This is not just a cosmetic nicety. The read end of a pipe will not generate an end of file condition if there are any writers with the pipe still open. In the case of the parent process, the rd.read will never return if it does not first issue a wr.close.

rd, wr = IO.pipe

if fork
  wr.close
  puts "Parent got: <#{rd.read}>"
  rd.close
  Process.wait
else
  rd.close
  puts "Sending message to parent"
  wr.write "Hi Dad"
  wr.close
end

produces:

  Sending message to parent
  Parent got: <Hi Dad>

IO::popen[править]


 IO.popen(cmd_string, mode="r" )               => io
 IO.popen(cmd_string, mode="r" ) {|io| block } => obj

Runs the specified command string as a subprocess; the subprocess's standard input and output will be connected to the returned IO object. If cmd_string starts with a ``-, then a new instance of Ruby is started as the subprocess. The default mode for the new file object is ``r, but mode may be set to any of the modes listed in the description for class IO. If a block is given, Ruby will run the command as a child connected to Ruby with a pipe. Ruby's end of the pipe will be passed as a parameter to the block. At the end of block, Ruby close the pipe and sets $?. In this case IO::popen returns the value of the block. If a block is given with a cmd_string of ``-, the block will be run in two separate processes: once in the parent, and once in a child. The parent process will be passed the pipe object as a parameter to the block, the child version of the block will be passed nil, and the child's standard in and standard out will be connected to the parent through the pipe. Not available on all platforms.

  f = IO.popen("uname")
  p f.readlines
  puts "Parent is #{Process.pid}"
  IO.popen ("date") { |f| puts f.gets }
  IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f}"}
  p $?

produces:

  ["Linux\n"]
  Parent is 26166
  Wed Apr  9 08:53:52 CDT 2003
  26169 is here, f is
  26166 is here, f is #<IO:0x401b3d44>
  #<Process::Status: pid=26166,exited(0)>

IO::read[править]


 IO.read(name, [length [, offset]] )   => string

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

  IO.read("testfile")           #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
  IO.read("testfile", 20)       #=> "This is line one\nThi"
  IO.read("testfile", 20, 10)   #=> "ne one\nThis is line "

IO::readlines[править]


 IO.readlines(name, sep_string=$/)   => array

Reads the entire file specified by name as individual lines, and returns those lines in an array. Lines are separated by sep_string.

  a = IO.readlines("testfile")
  a[0]   #=> "This is line one\n"

IO::select[править]


 IO.select(read_array 
 [, write_array 
 [, error_array 
 [, timeout]]] ) =>  array  or  nil

See Kernel#select.

IO::sysopen[править]


 IO.sysopen(path, [mode, [perm]])  => fixnum

Opens the given path, returning the underlying file descriptor as a Fixnum.

  IO.sysopen("testfile")   #=> 3

IO#<<[править]


 ios << obj     => ios

String Output---Writes obj to ios. obj will be converted to a string using to_s.

  $stdout << "Hello " << "world!\n"

produces:

  Hello world!

IO#binmode[править]


 ios.binmode    => ios

Puts ios into binary mode. This is useful only in MS-DOS/Windows environments. Once a stream is in binary mode, it cannot be reset to nonbinary mode.

IO#block_scanf[править]


 block_scanf(str) {|current| ...}

(нет описания...)

IO#close[править]


 ios.close   => nil

Closes ios and flushes any pending writes to the operating system. The stream is unavailable for any further data operations; an IOError is raised if such an attempt is made. I/O streams are automatically closed when they are claimed by the garbage collector. If ios is opened by IO.popen, close sets $?.

IO#close_read[править]


 ios.close_read    => nil

Closes the read end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe). Will raise an IOError if the stream is not duplexed.

  f = IO.popen("/bin/sh","r+")
  f.close_read
  f.readlines

produces:

  prog.rb:3:in `readlines': not opened for reading (IOError)
   from prog.rb:3

IO#close_write[править]


 ios.close_write   => nil

Closes the write end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe). Will raise an IOError if the stream is not duplexed.

  f = IO.popen("/bin/sh","r+")
  f.close_write
  f.print "nowhere"

produces:

  prog.rb:3:in `write': not opened for writing (IOError)
   from prog.rb:3:in `print'
   from prog.rb:3

IO#closed?[править]


 ios.closed?    => true or false

Returns true if ios is completely closed (for duplex streams, both reader and writer), false otherwise.

  f = File.new("testfile")
  f.close         #=> nil
  f.closed?       #=> true
  f = IO.popen("/bin/sh","r+")
  f.close_write   #=> nil
  f.closed?       #=> false
  f.close_read    #=> nil
  f.closed?       #=> true

IO#each[править]


 ios.each(sep_string=$/)      {|line| block }  => ios
 ios.each_line(sep_string=$/) {|line| block }  => ios

Executes the block for every line in ios, where lines are separated by sep_string. ios must be opened for reading or an IOError will be raised.

  f = File.new("testfile")
  f.each {|line| puts "#{f.lineno}: #{line}" }

produces:

  1: This is line one
  2: This is line two
  3: This is line three
  4: And so on...

IO#each_byte[править]


 ios.each_byte {|byte| block }  => nil

Calls the given block once for each byte (0..255) in ios, passing the byte as an argument. The stream must be opened for reading or an IOError will be raised.

  f = File.new("testfile")
  checksum = 0
  f.each_byte {|x| checksum ^= x }   #=> #<File:testfile>
  checksum                           #=> 12

IO#each_line[править]


 ios.each(sep_string=$/)      {|line| block }  => ios
 ios.each_line(sep_string=$/) {|line| block }  => ios

Executes the block for every line in ios, where lines are separated by sep_string. ios must be opened for reading or an IOError will be raised.

  f = File.new("testfile")
  f.each {|line| puts "#{f.lineno}: #{line}" }

produces:

  1: This is line one
  2: This is line two
  3: This is line three
  4: And so on...

IO#eof[править]


 ios.eof     => true or false
 ios.eof?    => true or false

Returns true if ios is at end of file that means there are no more data to read. The stream must be opened for reading or an IOError will be raised.

  f = File.new("testfile")
  dummy = f.readlines
  f.eof   #=> true

If ios is a stream such as pipe or socket, IO#eof? blocks until the other end sends some data or closes it.

  r, w = IO.pipe
  Thread.new { sleep 1; w.close }
  r.eof?  #=> true after 1 second blocking
  r, w = IO.pipe
  Thread.new { sleep 1; w.puts "a" }
  r.eof?  #=> false after 1 second blocking
  r, w = IO.pipe
  r.eof?  # blocks forever

Note that IO#eof? reads data to a input buffer. So IO#sysread doesn't work with IO#eof?.

IO#eof?[править]


 ios.eof     => true or false
 ios.eof?    => true or false

Returns true if ios is at end of file that means there are no more data to read. The stream must be opened for reading or an IOError will be raised.

  f = File.new("testfile")
  dummy = f.readlines
  f.eof   #=> true

If ios is a stream such as pipe or socket, IO#eof? blocks until the other end sends some data or closes it.

  r, w = IO.pipe
  Thread.new { sleep 1; w.close }
  r.eof?  #=> true after 1 second blocking
  r, w = IO.pipe
  Thread.new { sleep 1; w.puts "a" }
  r.eof?  #=> false after 1 second blocking
  r, w = IO.pipe
  r.eof?  # blocks forever

Note that IO#eof? reads data to a input buffer. So IO#sysread doesn't work with IO#eof?.

IO#fcntl[править]


 ios.fcntl(integer_cmd, arg)    => integer

Provides a mechanism for issuing low-level commands to control or query file-oriented I/O streams. Arguments and results are platform dependent. If arg is a number, its value is passed directly. If it is a string, it is interpreted as a binary sequence of bytes (Array#pack might be a useful way to build this string). On Unix platforms, see fcntl(2) for details. Not implemented on all platforms.

IO#fileno[править]


 ios.fileno    => fixnum
 ios.to_i      => fixnum

Returns an integer representing the numeric file descriptor for ios.

  $stdin.fileno    #=> 0
  $stdout.fileno   #=> 1

(еще известен как to_i)

IO#flush[править]


 ios.flush    => ios

Flushes any buffered data within ios to the underlying operating system (note that this is Ruby internal buffering only; the OS may buffer the data as well).

  $stdout.print "no newline"
  $stdout.flush

produces:

  no newline

IO#fsync[править]


 ios.fsync   => 0 or nil

Immediately writes all buffered data in ios to disk. Returns nil if the underlying operating system does not support fsync(2). Note that fsync differs from using IO#sync=. The latter ensures that data is flushed from Ruby's buffers, but doesn't not guarantee that the underlying operating system actually writes it to disk.

IO#getc[править]


 ios.getc   => fixnum or nil

Gets the next 8-bit byte (0..255) from ios. Returns nil if called at end of file.

  f = File.new("testfile")
  f.getc   #=> 84
  f.getc   #=> 104

IO#gets[править]


 ios.gets(sep_string=$/)   => string or nil

Reads the next ``line from the I/O stream; lines are separated by sep_string. A separator of nil reads the entire contents, and a zero-length separator reads the input a paragraph at a time (two successive newlines in the input separate paragraphs). The stream must be opened for reading or an IOError will be raised. The line read in will be returned and also assigned to $_. Returns nil if called at end of file.

  File.new("testfile").gets   #=> "This is line one\n"
  $_                          #=> "This is line one\n"

IO#inspect[править]


 ios.inspect   => string

Return a string describing this IO object.

IO#ioctl[править]


 ios.ioctl(integer_cmd, arg)    => integer

Provides a mechanism for issuing low-level commands to control or query I/O devices. Arguments and results are platform dependent. If arg is a number, its value is passed directly. If it is a string, it is interpreted as a binary sequence of bytes. On Unix platforms, see ioctl(2) for details. Not implemented on all platforms.

IO#isatty[править]


 ios.isatty   => true or false
 ios.tty?     => true or false

Returns true if ios is associated with a terminal device (tty), false otherwise.

  File.new("testfile").isatty   #=> false
  File.new("/dev/tty").isatty   #=> true

IO#lineno[править]


 ios.lineno    => integer

Returns the current line number in ios. The stream must be opened for reading. lineno counts the number of times gets is called, rather than the number of newlines encountered. The two values will differ if gets is called with a separator other than newline. See also the $. variable.

  f = File.new("testfile")
  f.lineno   #=> 0
  f.gets     #=> "This is line one\n"
  f.lineno   #=> 1
  f.gets     #=> "This is line two\n"
  f.lineno   #=> 2

IO#lineno=[править]


 ios.lineno = integer    => integer

Manually sets the current line number to the given value. $. is updated only on the next read.

  f = File.new("testfile")
  f.gets                     #=> "This is line one\n"
  $.                         #=> 1
  f.lineno = 1000
  f.lineno                   #=> 1000
  $. # lineno of last read   #=> 1
  f.gets                     #=> "This is line two\n"
  $. # lineno of last read   #=> 1001

IO#pid[править]


 ios.pid    => fixnum

Returns the process ID of a child process associated with ios. This will be set by IO::popen.

  pipe = IO.popen("-")
  if pipe
    $stderr.puts "In parent, child pid is #{pipe.pid}"
  else
    $stderr.puts "In child, pid is #{$$}"
  end

produces:

  In child, pid is 26209
  In parent, child pid is 26209

IO#pos[править]


 ios.pos     => integer
 ios.tell    => integer

Returns the current offset (in bytes) of ios.

  f = File.new("testfile")
  f.pos    #=> 0
  f.gets   #=> "This is line one\n"
  f.pos    #=> 17

IO#pos=[править]


 ios.pos = integer    => integer

Seeks to the given position (in bytes) in ios.

  f = File.new("testfile")
  f.pos = 17
  f.gets   #=> "This is line two\n"

IO#print[править]


 ios.print()             => nil
 ios.print(obj, ...)     => nil

Writes the given object(s) to ios. The stream must be opened for writing. If the output record separator ($\) is not nil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren't strings will be converted by calling their to_s method. With no argument, prints the contents of the variable $_. Returns nil.

  $stdout.print("This is ", 100, " percent.\n")

produces:

  This is 100 percent.

IO#printf[править]


 ios.printf(format_string [, obj, ...] )   => nil

Formats and writes to ios, converting parameters under control of the format string. See Kernel#sprintf for details.

IO#putc[править]


 ios.putc(obj)    => obj

If obj is Numeric, write the character whose code is obj, otherwise write the first character of the string representation of obj to ios.

  $stdout.putc "A"
  $stdout.putc 65

produces:

  AA

IO#puts[править]


 ios.puts(obj, ...)    => nil

Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.

  $stdout.puts("this", "is", "a", "test")

produces:

  this
  is
  a
  test

IO#read[править]


 ios.read([length [, buffer]])    => string, buffer, or nil

Reads at most length bytes from the I/O stream, or to the end of file if length is omitted or is nil. length must be a non-negative integer or nil. If the optional buffer argument is present, it must reference a String, which will receive the data. At end of file, it returns nil or "" depend on length. ios.read() and ios.read(nil) returns "". ios.read(positive-integer) returns nil.

  f = File.new("testfile")
  f.read(16)   #=> "This is line one"

IO#read_nonblock[править]


 ios.read_nonblock(maxlen)              => string
 ios.read_nonblock(maxlen, outbuf)      => outbuf

Reads at most maxlen bytes from ios using read(2) system call after O_NONBLOCK is set for the underlying file descriptor. If the optional outbuf argument is present, it must reference a String, which will receive the data. read_nonblock just calls read(2). It causes all errors read(2) causes: EAGAIN, EINTR, etc. The caller should care such errors. read_nonblock causes EOFError on EOF. If the read buffer is not empty, read_nonblock reads from the buffer like readpartial. In this case, read(2) is not called.

IO#readbytes[править]


 readbytes(n)

Reads exactly n bytes. If the data read is nil an EOFError is raised. If the data read is too short a TruncatedDataError is raised and the read data is obtainable via its #data method.

IO#readchar[править]


 ios.readchar   => fixnum

Reads a character as with IO#getc, but raises an EOFError on end of file.

IO#readline[править]


 ios.readline(sep_string=$/)   => string

Reads a line as with IO#gets, but raises an EOFError on end of file.

IO#readlines[править]


 ios.readlines(sep_string=$/)  =>   array

Reads all of the lines in ios, and returns them in anArray. Lines are separated by the optional sep_string. If sep_string is nil, the rest of the stream is returned as a single record. The stream must be opened for reading or an IOError will be raised.

  f = File.new("testfile")
  f.readlines[0]   #=> "This is line one\n"

IO#readpartial[править]


 ios.readpartial(maxlen)              => string
 ios.readpartial(maxlen, outbuf)      => outbuf

Reads at most maxlen bytes from the I/O stream. It blocks only if ios has no data immediately available. It doesn't block if some data available. If the optional outbuf argument is present, it must reference a String, which will receive the data. It raises EOFError on end of file. readpartial is designed for streams such as pipe, socket, tty, etc. It blocks only when no data immediately available. This means that it blocks only when following all conditions hold.

  • the buffer in the IO object is empty.
  • the content of the stream is empty.
  • the stream is not reached to EOF.

When readpartial blocks, it waits data or EOF on the stream. If some data is reached, readpartial returns with the data. If EOF is reached, readpartial raises EOFError. When readpartial doesn't blocks, it returns or raises immediately. If the buffer is not empty, it returns the data in the buffer. Otherwise if the stream has some content, it returns the data in the stream. Otherwise if the stream is reached to EOF, it raises EOFError.

  r, w = IO.pipe           #               buffer          pipe content
  w << "abc"               #               ""              "abc".
  r.readpartial(4096)      #=> "abc"       ""              ""
  r.readpartial(4096)      # blocks because buffer and pipe is empty.
  r, w = IO.pipe           #               buffer          pipe content
  w << "abc"               #               ""              "abc"
  w.close                  #               ""              "abc" EOF
  r.readpartial(4096)      #=> "abc"       ""              EOF
  r.readpartial(4096)      # raises EOFError
  r, w = IO.pipe           #               buffer          pipe content
  w << "abc\ndef\n"        #               ""              "abc\ndef\n"
  r.gets                   #=> "abc\n"     "def\n"         ""
  w << "ghi\n"             #               "def\n"         "ghi\n"
  r.readpartial(4096)      #=> "def\n"     ""              "ghi\n"
  r.readpartial(4096)      #=> "ghi\n"     ""              ""

Note that readpartial behaves similar to sysread. The differences are:

  • If the buffer is not empty, read from the buffer instead of "sysread for buffered IO (IOError)".
  • It doesn't cause Errno::EAGAIN and Errno::EINTR. When readpartial meets EAGAIN and EINTR by read system call, readpartial retry the system call.

The later means that readpartial is nonblocking-flag insensitive. It blocks on the situation IO#sysread causes Errno::EAGAIN as if the fd is blocking mode.

IO#reopen[править]


 ios.reopen(other_IO)         => ios 
 ios.reopen(path, mode_str)   => ios

Reassociates ios with the I/O stream given in other_IO or to a new stream opened on path. This may dynamically change the actual class of this stream.

  f1 = File.new("testfile")
  f2 = File.new("testfile")
  f2.readlines[0]   #=> "This is line one\n"
  f2.reopen(f1)     #=> #<File:testfile>
  f2.readlines[0]   #=> "This is line one\n"

IO#rewind[править]


 ios.rewind    => 0

Positions ios to the beginning of input, resetting lineno to zero.

  f = File.new("testfile")
  f.readline   #=> "This is line one\n"
  f.rewind     #=> 0
  f.lineno     #=> 0
  f.readline   #=> "This is line one\n"

IO#scanf[править]


 scanf(str,&b)

The trick here is doing a match where you grab one line of input at a time. The linebreak may or may not occur at the boundary where the string matches a format specifier. And if it does, some rule about whitespace may or may not be in effect... That's why this is much more elaborate than the string version. For each line: Match succeeds (non-emptily) and the last attempted spec/string sub-match succeeded:

 could the last spec keep matching?
   yes: save interim results and continue (next line)

The last attempted spec/string did not match: are we on the next-to-last spec in the string?

 yes:
   is fmt_string.string_left all spaces?
     yes: does current spec care about input space?
       yes: fatal failure
       no: save interim results and continue
 no: continue  [this state could be analyzed further]

IO#seek[править]


 ios.seek(amount, whence=SEEK_SET) -> 0

Seeks to a given offset anInteger in the stream according to the value of whence:

 IO::SEEK_CUR  | Seeks to amount plus current position
 --------------+----------------------------------------------------
 IO::SEEK_END  | Seeks to amount plus end of stream (you probably
               | want a negative value for amount)
 --------------+----------------------------------------------------
 IO::SEEK_SET  | Seeks to the absolute location given by amount

Example:

  f = File.new("testfile")
  f.seek(-13, IO::SEEK_END)   #=> 0
  f.readline                  #=> "And so on...\n"

IO#soak_up_spaces[править]


 soak_up_spaces()

(нет описания...)

IO#stat[править]


 ios.stat    => stat

Returns status information for ios as an object of type File::Stat.

  f = File.new("testfile")
  s = f.stat
  "%o" % s.mode   #=> "100644"
  s.blksize       #=> 4096
  s.atime         #=> Wed Apr 09 08:53:54 CDT 2003

IO#sync[править]


 ios.sync    => true or false

Returns the current ``sync mode of ios. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered by Ruby internally. See also IO#fsync.

  f = File.new("testfile")
  f.sync   #=> false

IO#sync=[править]


 ios.sync = boolean   => boolean

Sets the ``sync mode to true or false. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered internally. Returns the new state. See also IO#fsync.

  f = File.new("testfile")
  f.sync = true

(produces no output)

IO#sysread[править]


 ios.sysread(integer )    => string

Reads integer bytes from ios using a low-level read and returns them as a string. Do not mix with other methods that read from ios or you may get unpredictable results. Raises SystemCallError on error and EOFError at end of file.

  f = File.new("testfile")
  f.sysread(16)   #=> "This is line one"

IO#sysseek[править]


 ios.sysseek(offset, whence=SEEK_SET)   => integer

Seeks to a given offset in the stream according to the value of whence (see IO#seek for values of whence). Returns the new offset into the file.

  f = File.new("testfile")
  f.sysseek(-13, IO::SEEK_END)   #=> 53
  f.sysread(10)                  #=> "And so on."

IO#syswrite[править]


 ios.syswrite(string)   => integer

Writes the given string to ios using a low-level write. Returns the number of bytes written. Do not mix with other methods that write to ios or you may get unpredictable results. Raises SystemCallError on error.

  f = File.new("out", "w")
  f.syswrite("ABCDEF")   #=> 6

IO#tell[править]


 ios.pos     => integer
 ios.tell    => integer

Returns the current offset (in bytes) of ios.

  f = File.new("testfile")
  f.pos    #=> 0
  f.gets   #=> "This is line one\n"
  f.pos    #=> 17

IO#to_i[править]


 to_i()

Alias for #fileno

IO#to_io[править]


 ios.to_io -> ios

Returns ios.

IO#tty?[править]


 ios.isatty   => true or false
 ios.tty?     => true or false

Returns true if ios is associated with a terminal device (tty), false otherwise.

  File.new("testfile").isatty   #=> false
  File.new("/dev/tty").isatty   #=> true

IO#ungetc[править]


 ios.ungetc(integer)   => nil

Pushes back one character (passed as a parameter) onto ios, such that a subsequent buffered read will return it. Only one character may be pushed back before a subsequent read operation (that is, you will be able to read only the last of several characters that have been pushed back). Has no effect with unbuffered reads (such as IO#sysread).

  f = File.new("testfile")   #=> #<File:testfile>
  c = f.getc                 #=> 84
  f.ungetc(c)                #=> nil
  f.getc                     #=> 84

IO#write[править]


 ios.write(string)    => integer

Writes the given string to ios. The stream must be opened for writing. If the argument is not a string, it will be converted to a string using to_s. Returns the number of bytes written.

  count = $stdout.write( "This is a test\n" )
  puts "That was #{count} bytes of data"

produces:

  This is a test
  That was 15 bytes of data

IO#write_nonblock[править]


 ios.write_nonblock(string)   => integer

Writes the given string to ios using write(2) system call after O_NONBLOCK is set for the underlying file descriptor. write_nonblock just calls write(2). It causes all errors write(2) causes: EAGAIN, EINTR, etc. The result may also be smaller than string.length (partial write). The caller should care such errors and partial write.

Класс Integer < Numeric[править]

Integer — это родительский класс для классов Bignum и Fixnum, которые отвечают за работу с целыми числами.


Примеси

Precision (prec, prec_f, prec_i)

Методы класса

from_prime_division, induced_from

Методы объекта

ceil, chr, denominator, downto, even?, floor, gcdlcm, gcd, integer?, lcm, next, numerator, odd?, prime_division, round, succ, times, to_f, to_int, to_i, to_r, to_s, truncate, upto

Integer::from_prime_division[править]


Integer::from_prime_division( ''array'' )   #-> integer

Преобразует двумерный массив array из простых делителей и их степеней обратно в целое число.

require 'mathn'
Integer.from_prime_division( [[5,1], [7,1]] )      #-> 35
Integer.from_prime_division( 122.prime_division )  #-> 122
Информация

Полезно посмотреть на метод prime_division, который имеет схожую функциональность

Integer::induced_from[править]


Integer.induced_from(obj)    #-> integer

Преобразует obj в целое число.

Integer#ceil[править]


int.to_i      #-> int
int.to_int    #-> int
int.floor     #-> int
int.ceil      #-> int
int.round     #-> int
int.truncate  #-> int

В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.

Информация

Полезно посмотреть на методы ceil, floor, round, to_i, to_int и truncate, которые имеют схожую функциональность

Integer#chr[править]


int.chr    #-> string

Возвращает строку, состоящую из ASCII-символа с кодом равным значению int.

65.chr    #-> "A"
?a.chr    #=> "a"
230.chr   #=> "\346"

Integer#denominator[править]


num.denominator   #-> 1

Для целого числа знаменатель всегда равен 1. Поэтому, данный метод возвращает 1.

Информация

Знаменатель отличен от 1 только у рациональных дробей. Данный метод создан для совместимости, так как целые числа — это частный случай рациональных дробей. Формально, целое число — это рациональная дробь у которой знаменатель равен 1

Integer#downto[править]


int.downto(limit) {|i| block }     #-> int

Выполняет блок для всех чисел с int по limit с шагом -1 (то есть число int должно быть больше числа limit).

5.downto(1) { |n| print n, ".. " }
print "  Liftoff!\n"

результат:

 5.. 4.. 3.. 2.. 1..   Liftoff!

Integer#even?[править]


num.even?  #->  true или false

Возвращает true, если int - четное число.

Integer#floor[править]


int.to_i      #-> int
int.to_int    #-> int
int.floor     #-> int
int.ceil      #-> int
int.round     #-> int
int.truncate  #-> int

В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.

Информация

Полезно посмотреть на методы ceil, floor, round, to_i, to_int и truncate, которые имеют схожую функциональность

Integer#gcd[править]


num.gcd(other)

Возвращает наибольший общий делитель двух чисел (num и other).

72.gcd 168           #-> 24
19.gcd 36            #-> 1
Информация

Результат данного метода — положительное целое число, независимо от знака аргументов

Информация

Полезно посмотреть на методы gcd и gcdlcm, которые имеют схожую функциональность

Integer#gcdlcm[править]


num.gcdlcm(other)

Возвращает НОД и НОК (см. gcd и lcm) двух чисел (num и other). Этот метод особенно эффективен, когда необходимо посчитать НОД и НОК одновременно.

6.gcdlcm 9     #-> [3, 18]
Информация

Полезно посмотреть на методы gcd и lcm, которые имеют схожую функциональность

Integer#integer?[править]


int.integer? #-> true

Всегда возвращает true.

Integer#lcm[править]


num.lcm(other)  #-> integer

Возвращает наименьшее общее кратное двух чисел (num и other).

6.lcm 7        #-> 42
6.lcm 9        #-> 18
Информация

Результат данного метода — положительное целое число, независимо от знака каждого из аргументов

Информация

Полезно посмотреть на методы gcd и gcdlcm, которые имеют схожую функциональность

Integer#next[править]


int.next    #-> int
int.succ    #-> int

Возвращает целое число, которое равно int + 1.

1.next      #-> 2
(-1).next   #-> 0
Информация

Методы succ и next — абсолютно идентичны, то есть являются именами одного и того же метода

Integer#numerator[править]


num.numerator  #-> num

Для целого числа числитель всегда равен его значению. Поэтому данный метод возвращает значение num.

Информация

Полезно посмотреть на метод denominator, который имеет схожую функциональность

Integer#odd?[править]


num.odd?  #->  true или false

Возвращает true, если int - нечетное число.

Integer#prime_division[править]


num.prime_division   #-> array

Возвращает двумерный массив, состоящий из простых делителей числа и их степеней.

require 'mathn'
35.prime_division    #-> [[5, 1], [7, 1]]
256.prime_division   #-> [[2, 8]]
Информация

Полезно посмотреть на метод from_prime_division, который имеет схожую функциональность

Integer#round[править]


int.to_i      #-> int
int.to_int    #-> int
int.floor     #-> int
int.ceil      #-> int
int.round     #-> int
int.truncate  #-> int

В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.

Информация

Полезно посмотреть на методы ceil, floor, round, to_i, to_int и truncate, которые имеют схожую функциональность

Integer#succ[править]


int.next    #-> int
int.succ    #-> int

Возвращает целое число, которое равно int + 1.

1.next      #-> 2
(-1).next   #-> 0
Информация

Методы succ и next — абсолютно идентичны, то есть являются именами одного и того же метода

Integer#times[править]


int.times {|i| block }     #-> int

Выполняет блок int раз, передавая в него значения от 0 до int - 1.

5.times do |i|
  print i, " "
end

результат:

 0 1 2 3 4

Integer#to_f[править]


int.to_f      #-> float

Преобразует int в Float. Если int не помещается в Float, результатом будет бесконечность.

108.to_f #-> 108.0
Информация

Подробнее об Float

Integer#to_i[править]


int.to_i      #-> int
int.to_int    #-> int
int.floor     #-> int
int.ceil      #-> int
int.round     #-> int
int.truncate  #-> int

В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.

Информация

Полезно посмотреть на методы ceil, floor, round, to_i, to_int и truncate, которые имеют схожую функциональность

Integer#to_int[править]


int.to_i      #-> int
int.to_int    #-> int
int.floor     #-> int
int.ceil      #-> int
int.round     #-> int
int.truncate  #-> int

В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.

Информация

Полезно посмотреть на методы ceil, floor, round, to_i, to_int и truncate, которые имеют схожую функциональность

Integer#to_r[править]


num.to_r   #-> rational

Возвращает число num в виде рациональной дроби.

35.to_r   #-> Rational(35, 1)

Integer#to_s[править]


int.to_s(base=10) #-> string

Возвращает строку, содержащую представление разряда int с основанием системы счисления (от 2 до 36).

12345.to_s       #=> "12345"
12345.to_s(2)    #=> "11000000111001"
12345.to_s(8)    #=> "30071"
12345.to_s(10)   #=> "12345"
12345.to_s(16)   #=> "3039"
12345.to_s(36)   #=> "9ix"
78546939656932.to_s(36)  #=> "rubyrules"
Информация

Также имеет псевдоним: инспектировать

Integer#truncate[править]


int.to_i      #-> int
int.to_int    #-> int
int.floor     #-> int
int.ceil      #-> int
int.round     #-> int
int.truncate  #-> int

В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.

Информация

Полезно посмотреть на методы ceil, to_i, to_int, floor, round и truncate, которые имеют схожую функциональность

Integer#upto[править]


int.upto(limit) {|i| block }     #-> int

Выполняет блок для всех целых чисел с int по limit, включительно.

5.upto(10) { |i| print i, " " }

результат:

 5 6 7 8 9 10

Примесь Kernel[править]

Since Ruby is very dynamic, methods added to the ancestors of BlankSlate after BlankSlate is defined will show up in the list of available BlankSlate methods. We handle this by defining a hook in the Object and Kernel classes that will hide any defined


Some objects are dupable, some are not. So we define a version of dup (called rake_dup) that returns self on the handful of classes that are not dupable.


Create a global fork method


Методы объекта

Array, Float, Integer, Pathname, String, URI, `, abort, at_exit, autoload?, autoload, binding, block_given?, callcc, caller, catch, chomp!, chomp, chop!, chop, eval, exec, exit!, exit, fail, fork, format, gem, getc, gets, global_variables, gsub!, gsub, iterator?, lambda, load, local_variables, loop, method_missing, open_uri_original_open, open, pp, pretty_inspect, printf, print, proc, putc, puts, p, raise, rake_dup, rand, readlines, readline, require_gem, require, scanf, scan, select, set_trace_func, sleep, split, sprintf, srand, sub!, sub, syscall, system, test, throw, to_ptr, trace_var, trap, untrace_var, warn, y

Kernel#Array[править]


 Array(arg)    => array

Returns arg as an Array. First tries to call arg.to_ary, then arg.to_a. If both fail, creates a single element array containing arg (unless arg is nil).

  Array(1..5)   #=> [1, 2, 3, 4, 5]

Kernel#Float[править]


 Float(arg)    => float

Returns arg converted to a float. Numeric types are converted directly, the rest are converted using arg.to_f. As of Ruby 1.8, converting nil generates a TypeError.

  Float(1)           #=> 1.0
  Float("123.456")   #=> 123.456

Kernel#Integer[править]


 Integer(arg)    => integer

Converts arg to a Fixnum or Bignum. Numeric types are converted directly (with floating point numbers being truncated). If arg is a String, leading radix indicators (0, 0b, and 0x) are honored. Others are converted using to_int and to_i. This behavior is different from that of String#to_i.

  Integer(123.999)    #=> 123
  Integer("0x1a")     #=> 26
  Integer(Time.new)   #=> 1049896590

Kernel#Pathname[править]


 Pathname(path)

create a pathname object. This method is available since 1.8.5.

Kernel#String[править]


 String(arg)   => string

Converts arg to a String by calling its to_s method.

  String(self)        #=> "main"
  String(self.class   #=> "Object"
  String(123456)      #=> "123456"

Kernel#URI[править]


 URI(uri_str)

alias for URI.parse. This method is introduced at 1.8.2.

Kernel#`[править]


 `cmd`    => string

Returns the standard output of running cmd in a subshell. The built-in syntax %x{...} uses this method. Sets $? to the process status.

  `date`                   #=> "Wed Apr  9 08:56:30 CDT 2003\n"
  `ls testdir`.split[1]    #=> "main.rb"
  `echo oops && exit 99`   #=> "oops\n"
  $?.exitstatus            #=> 99

Kernel#abort[править]


 abort
 Kernel::abort
 Process::abort

Terminate execution immediately, effectively by calling Kernel.exit(1). If msg is given, it is written to STDERR prior to terminating.

Kernel#at_exit[править]


 at_exit { block } -> proc

Converts block to a Proc object (and therefore binds it at the point of call) and registers it for execution when the program exits. If multiple handlers are registered, they are executed in reverse order of registration.

  def do_at_exit(str1)
    at_exit { print str1 }
  end
  at_exit { puts "cruel world" }
  do_at_exit("goodbye ")
  exit

produces:

  goodbye cruel world

Kernel#autoload[править]


 autoload(module, filename)   => nil

Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.

  autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")

Kernel#autoload?[править]


 autoload(module, filename)   => nil

Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.

  autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")

Kernel#binding[править]


 binding -> a_binding

Returns a Binding object, describing the variable and method bindings at the point of call. This object can be used when calling eval to execute the evaluated command in this environment. Also see the description of class Binding.

  def getBinding(param)
    return binding
  end
  b = getBinding("hello")
  eval("param", b)   #=> "hello"

Kernel#block_given?[править]


 block_given?   => true or false
 iterator?      => true or false

Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.

  def try
    if block_given?
      yield
    else
      "no block"
    end
  end
  try                  #=> "no block"
  try { "hello" }      #=> "hello"
  try do "hello" end   #=> "hello"

Kernel#callcc[править]


 callcc {|cont| block }   =>  obj

Generates a Continuation object, which it passes to the associated block. Performing a cont.call will cause the callcc to return (as will falling through the end of the block). The value returned by the callcc is the value of the block, or the value passed to cont.call. See class Continuation for more details. Also see Kernel::throw for an alternative mechanism for unwinding a call stack.

Kernel#caller[править]


 caller(start=1)    => array

Returns the current execution stack---an array containing strings in the form ``file:line or ``file:line: in `method'. The optional start parameter determines the number of initial stack entries to omit from the result.

  def a(skip)
    caller(skip)
  end
  def b(skip)
    a(skip)
  end
  def c(skip)
    b(skip)
  end
  c(0)   #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
  c(1)   #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
  c(2)   #=> ["prog:8:in `c'", "prog:12"]
  c(3)   #=> ["prog:13"]

Kernel#catch[править]


 catch(symbol) {| | block }  > obj

catch executes its block. If a throw is executed, Ruby searches up its stack for a catch block with a tag corresponding to the throw's symbol. If found, that block is terminated, and catch returns the value given to throw. If throw is not called, the block terminates normally, and the value of catch is the value of the last expression evaluated. catch expressions may be nested, and the throw call need not be in lexical scope.

  def routine(n)
    puts n
    throw :done if n <= 0
    routine(n-1)
  end
  catch(:done) { routine(3) }

produces:

  3
  2
  1
  0

Kernel#chomp[править]


 chomp            => $_
 chomp(string)    => $_

Equivalent to $_ = $_.chomp(string). See String#chomp.

  $_ = "now\n"
  chomp         #=> "now"
  $_            #=> "now"
  chomp "ow"    #=> "n"
  $_            #=> "n"
  chomp "xxx"   #=> "n"
  $_            #=> "n"

Kernel#chomp![править]


 chomp!             => $_ or nil
 chomp!(string)     => $_ or nil

Equivalent to $_.chomp!(string). See String#chomp!

  $_ = "now\n"
  chomp!       #=> "now"
  $_           #=> "now"
  chomp! "x"   #=> nil
  $_           #=> "now"

Kernel#chop[править]


 chop   => string

Equivalent to ($_.dup).chop!, except nil is never returned. See String#chop!.

  a  =  "now\r\n"
  $_ = a
  chop   #=> "now"
  $_     #=> "now"
  chop   #=> "no"
  chop   #=> "n"
  chop   #=> ""
  chop   #=> ""
  a      #=> "now\r\n"

Kernel#chop![править]


 chop!    => $_ or nil

Equivalent to $_.chop!.

  a  = "now\r\n"
  $_ = a
  chop!   #=> "now"
  chop!   #=> "no"
  chop!   #=> "n"
  chop!   #=> ""
  chop!   #=> nil
  $_      #=> ""
  a       #=> ""

Kernel#eval[править]


 eval(string [, binding [, filename [,lineno]]])  => obj

Evaluates the Ruby expression(s) in string. If binding is given, the evaluation is performed in its context. The binding may be a Binding object or a Proc object. If the optional filename and lineno parameters are present, they will be used when reporting syntax errors.

  def getBinding(str)
    return binding
  end
  str = "hello"
  eval "str + ' Fred'"                      #=> "hello Fred"
  eval "str + ' Fred'", getBinding("bye")   #=> "bye Fred"

Kernel#exec[править]


 exec(command [, arg, ...])

Replaces the current process by running the given external command. If exec is given a single argument, that argument is taken as a line that is subject to shell expansion before being executed. If multiple arguments are given, the second and subsequent arguments are passed as parameters to command with no shell expansion. If the first argument is a two-element array, the first element is the command to be executed, and the second argument is used as the argv[0] value, which may show up in process listings. In MSDOS environments, the command is executed in a subshell; otherwise, one of the exec(2) system calls is used, so the running command may inherit some of the environment of the original program (including open file descriptors).

  exec "echo *"       # echoes list of files in current directory
  # never get here
  exec "echo", "*"    # echoes an asterisk
  # never get here

Kernel#exit[править]


 exit(integer=0)
 Kernel::exit(integer=0)
 Process::exit(integer=0)

Initiates the termination of the Ruby script by raising the SystemExit exception. This exception may be caught. The optional parameter is used to return a status code to the invoking environment.

  begin
    exit
    puts "never get here"
  rescue SystemExit
    puts "rescued a SystemExit exception"
  end
  puts "after begin block"

produces:

  rescued a SystemExit exception
  after begin block

Just prior to termination, Ruby executes any at_exit functions (see Kernel::at_exit) and runs any object finalizers (see ObjectSpace::define_finalizer).

  at_exit { puts "at_exit function" }
  ObjectSpace.define_finalizer("string",  proc { puts "in finalizer" })
  exit

produces:

  at_exit function
  in finalizer

Kernel#exit![править]


 Process.exit!(fixnum=-1)

Exits the process immediately. No exit handlers are run. fixnum is returned to the underlying system as the exit status.

  Process.exit!(0)

Kernel#fail[править]


 raise
 raise(string)
 raise(exception [, string [, array]])
 fail
 fail(string)
 fail(exception [, string [, array]])

With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.

  raise "Failed to create socket"
  raise ArgumentError, "No parameters", caller

Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

Kernel#fork, Kernel#fork===Kernel#format===


 format(format_string [, arguments...] )   => string
 sprintf(format_string [, arguments...] )  => string

Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:

 Flag     | Applies to   | Meaning
 ---------+--------------+-----------------------------------------
 space    | bdeEfgGiouxX | Leave a space at the start of
          |              | positive numbers.
 ---------+--------------+-----------------------------------------
 (digit)$ | all          | Specifies the absolute argument number
          |              | for this field. Absolute and relative
          |              | argument numbers cannot be mixed in a
          |              | sprintf string.
 ---------+--------------+-----------------------------------------
  #       | beEfgGoxX    | Use an alternative format. For the
          |              | conversions `o', `x', `X', and `b',
          |              | prefix the result with ``0, ``0x, ``0X,
          |              |  and ``0b, respectively. For `e',
          |              | `E', `f', `g', and 'G', force a decimal
          |              | point to be added, even if no digits follow.
          |              | For `g' and 'G', do not remove trailing zeros.
 ---------+--------------+-----------------------------------------
 +        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
 ---------+--------------+-----------------------------------------
 -        | all          | Left-justify the result of this conversion.
 ---------+--------------+-----------------------------------------
 0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
 ---------+--------------+-----------------------------------------
 *        | all          | Use the next argument as the field width.
          |              | If negative, left-justify the result. If the
          |              | asterisk is followed by a number and a dollar
          |              | sign, use the indicated argument as the width.

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field. For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.) The field types are:

   Field |  Conversion
   ------+--------------------------------------------------------------
     b   | Convert argument as a binary number.
     c   | Argument is the numeric code for a single character.
     d   | Convert argument as a decimal number.
     E   | Equivalent to `e', but uses an uppercase E to indicate
         | the exponent.
     e   | Convert floating point argument into exponential notation
         | with one digit before the decimal point. The precision
         | determines the number of fractional digits (defaulting to six).
     f   | Convert floating point argument as [-]ddd.ddd,
         |  where the precision determines the number of digits after
         | the decimal point.
     G   | Equivalent to `g', but use an uppercase `E' in exponent form.
     g   | Convert a floating point number using exponential form
         | if the exponent is less than -4 or greater than or
         | equal to the precision, or in d.dddd form otherwise.
     i   | Identical to `d'.
     o   | Convert argument as an octal number.
     p   | The valuing of argument.inspect.
     s   | Argument is a string to be substituted. If the format
         | sequence contains a precision, at most that many characters
         | will be copied.
     u   | Treat argument as an unsigned decimal number. Negative integers
         | are displayed as a 32 bit two's complement plus one for the
         | underlying architecture; that is, 2 ** 32 + n.  However, since
         | Ruby has no inherent limit on bits used to represent the
         | integer, this value is preceded by two dots (..) in order to
         | indicate a infinite number of leading sign bits.
     X   | Convert argument as a hexadecimal number using uppercase
         | letters. Negative numbers will be displayed with two
         | leading periods (representing an infinite string of
         | leading 'FF's.
     x   | Convert argument as a hexadecimal number.
         | Negative numbers will be displayed with two
         | leading periods (representing an infinite string of
         | leading 'ff's.

Examples:

  sprintf("%d %04x", 123, 123)               #=> "123 007b"
  sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
  sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
  sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
  sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
  sprintf("%u", -123)                        #=> "..4294967173"

Kernel#gem[править]


 gem(gem_name, *version_requirements)

Adds a Ruby Gem to the $LOAD_PATH. Before a Gem is loaded, its required Gems are loaded. If the version information is omitted, the highest version Gem of the supplied name is loaded. If a Gem is not found that meets the version requirement and/or a required Gem is not found, a Gem::LoadError is raised. More information on version requirements can be found in the Gem::Version documentation. The gem directive should be executed before any require statements (otherwise rubygems might select a conflicting library version). You can define the environment variable GEM_SKIP as a way to not load specified gems. you might do this to test out changes that haven't been intsalled yet. Example:

 GEM_SKIP=libA:libB ruby-I../libA -I../libB ./mycode.rb

[String or Gem::Dependency] The gem name or dependency instance. [default=">= 0.0.0"] The version requirement. [Boolean] true if the Gem is loaded, otherwise false.

[Gem::LoadError] if Gem cannot be found, is listed in GEM_SKIP, or version requirement not met.

Kernel#getc[править]


 getc()

obsolete

Kernel#gets[править]


 gets(separator=$/)    => string or nil

Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line. Returns nil at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If multiple filenames are present in ARGV, +gets(nil)+ will read the contents one file at a time.

  ARGV << "testfile"
  print while gets

produces:

  This is line one
  This is line two
  This is line three
  And so on...

The style of programming using $_ as an implicit parameter is gradually losing favor in the Ruby community.

Kernel#global_variables[править]


 global_variables    => array

Returns an array of the names of global variables.

  global_variables.grep /std/   #=> ["$stderr", "$stdout", "$stdin"]

Kernel#gsub[править]


 gsub(pattern, replacement)    => string
 gsub(pattern) {|...| block }  => string

Equivalent to $_.gsub..., except that $_ receives the modified result.

  $_ = "quick brown fox"
  gsub /[aeiou]/, '*'   #=> "q**ck br*wn f*x"
  $_                    #=> "q**ck br*wn f*x"

Kernel#gsub![править]


 gsub!(pattern, replacement)    => string or nil
 gsub!(pattern) {|...| block }  => string or nil

Equivalent to Kernel::gsub, except nil is returned if $_ is not modified.

  $_ = "quick brown fox"
  gsub! /cat/, '*'   #=> nil
  $_                 #=> "quick brown fox"

Kernel#iterator?[править]


 block_given?   => true or false
 iterator?      => true or false

Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.

  def try
    if block_given?
      yield
    else
      "no block"
    end
  end
  try                  #=> "no block"
  try { "hello" }      #=> "hello"
  try do "hello" end   #=> "hello"

Kernel#lambda[править]


 proc   { |...| block }  => a_proc
 lambda { |...| block }  => a_proc

Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.

Kernel#load[править]


 load(filename, wrap=false)   => true

Loads and executes the Ruby program in the file filename. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:. If the optional wrap parameter is true, the loaded script will be executed under an anonymous module, protecting the calling program's global namespace. In no circumstance will any local variables in the loaded file be propagated to the loading environment.

Kernel#local_variables[править]


 local_variables    => array

Returns the names of the current local variables.

  fred = 1
  for i in 1..10
     # ...
  end
  local_variables   #=> ["fred", "i"]

Kernel#loop[править]


 loop {|| block } 

Repeatedly executes the block.

  loop do
    print "Input: "
    line = gets
    break if !line or line =~ /^qQ/
    # ...
  end

Kernel#method_missing[править]


 obj.method_missing(symbol [, *args] )   => result

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.

  class Roman
    def romanToInt(str)
      # ...
    end
    def method_missing(methId)
      str = methId.id2name
      romanToInt(str)
    end
  end
  r = Roman.new
  r.iv      #=> 4
  r.xxiii   #=> 23
  r.mm      #=> 2000

Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

Kernel#open, Kernel#open_uri_original_open, Kernel#open===Kernel#open_uri_original_open===


 open_uri_original_open(...)

Alias for #open

Kernel#p[править]


 p(obj, ...)    => nil

For each object, directly writes obj.inspect followed by the current output record separator to the program's standard output.

  S = Struct.new(:name, :state)
  s = S['dave', 'TX']
  p s

produces:

  #<S name="dave", state="TX">

Kernel#pp[править]


 pp(*objs)

prints arguments in pretty form. pp returns nil.

Kernel#pretty_inspect[править]


 pretty_inspect()

returns a pretty printed object as a string.

Kernel#print[править]


 print(obj, ...)    => nil

Prints each object in turn to $stdout. If the output field separator ($,) is not nil, its contents will appear between each field. If the output record separator ($\) is not nil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren't strings will be converted by calling their to_s method.

  print "cat", [1,2,3], 99, "\n"
  $, = ", "
  $\ = "\n"
  print "cat", [1,2,3], 99

produces:

  cat12399
  cat, 1, 2, 3, 99

Kernel#printf[править]


 printf(io, string [, obj ... ] )    => nil
 printf(string [, obj ... ] )        => nil

Equivalent to:

  io.write(sprintf(string, obj, ...)

or

  $stdout.write(sprintf(string, obj, ...)

Kernel#proc[править]


 proc   { |...| block }  => a_proc
 lambda { |...| block }  => a_proc

Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.

Kernel#putc[править]


 putc(int)   => int

Equivalent to:

 $stdout.putc(int)

Kernel#puts[править]


 puts(obj, ..., ...)    => nil

Equivalent to

   $stdout.puts(obj, ...)

Kernel#raise[править]


 raise
 raise(string)
 raise(exception [, string [, array]])
 fail
 fail(string)
 fail(exception [, string [, array]])

With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.

  raise "Failed to create socket"
  raise ArgumentError, "No parameters", caller

Kernel#rake_dup[править]


 rake_dup()

Duplicate an object if it can be duplicated. If it can not be cloned or duplicated, then just return the original object.

Kernel#rand[править]


 rand(max=0)    => number

Converts max to an integer using max1 = max.to_i.abs. If the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0. Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max1. Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. Ruby currently uses a modified Mersenne Twister with a period of 219937-1.

  srand 1234                 #=> 0
  [ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]
  [ rand(10), rand(1000) ]   #=> [6, 817]
  srand 1234                 #=> 1234
  [ rand,  rand ]            #=> [0.191519450163469, 0.49766366626136]

Kernel#readline[править]


 readline(separator=$/)   => string

Equivalent to Kernel::gets, except readline raises EOFError at end of file.

Kernel#readlines[править]


 readlines(separator=$/)    => array

Returns an array containing the lines returned by calling Kernel.gets(separator) until the end of file.

Kernel#require[править]


 require(string)    => true or false

Ruby tries to load the library named string, returning true if successful. If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $:. If the file has the extension ``.rb, it is loaded as a source file; if the extension is ``.so, ``.o, or ``.dll, or whatever the default shared library extension is on the current platform, Ruby loads the shared library as a Ruby extension. Otherwise, Ruby tries adding ``.rb, ``.so, and so on to the name. The name of the loaded feature is added to the array in $". A feature will not be loaded if it's name already appears in $". However, the file name is not converted to an absolute path, so that ``require 'a';require './a' will load a.rb twice.

  require "my-library.rb"
  require "db-driver"

Kernel#require_gem[править]


 require_gem(gem_name, *version_requirements)

Same as the gem command, but will also require a file if the gem provides an auto-required file name. DEPRECATED! Use gem instead.

Kernel#scan[править]


 scan(pattern)                   => array
 scan(pattern) {|///| block }    => $_

Equivalent to calling $_.scan. See String#scan.

Kernel#scanf[править]


 scanf(fs,&b)

(нет описания...)

Kernel#select[править]


 IO.select(read_array 
 [, write_array 
 [, error_array 
 [, timeout]]] ) =>  array  or  nil

See Kernel#select.

Kernel#set_trace_func[править]


 set_trace_func(proc)    => proc
 set_trace_func(nil)     => nil

Establishes proc as the handler for tracing, or disables tracing if the parameter is nil. proc takes up to six parameters: an event name, a filename, a line number, an object id, a binding, and the name of a class. proc is invoked whenever an event occurs. Events are: c-call (call a C-language routine), c-return (return from a C-language routine), call (call a Ruby method), class (start a class or module definition), end (finish a class or module definition), line (execute code on a new line), raise (raise an exception), and return (return from a Ruby method). Tracing is disabled within the context of proc.

   class Test
   def test
     a = 1
     b = 2
   end
   end
   set_trace_func proc { |event, file, line, id, binding, classname|
      printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
   }
   t = Test.new
   t.test
     line prog.rb:11               false
   c-call prog.rb:11        new    Class
   c-call prog.rb:11 initialize   Object
 c-return prog.rb:11 initialize   Object
 c-return prog.rb:11        new    Class
     line prog.rb:12               false
     call prog.rb:2        test     Test
     line prog.rb:3        test     Test
     line prog.rb:4        test     Test
   return prog.rb:4        test     Test

Kernel#sleep[править]


 sleep([duration])    => fixnum

Suspends the current thread for duration seconds (which may be any number, including a Float with fractional seconds). Returns the actual number of seconds slept (rounded), which may be less than that asked for if another thread calls Thread#run. Zero arguments causes sleep to sleep forever.

  Time.new    #=> Wed Apr 09 08:56:32 CDT 2003
  sleep 1.2   #=> 1
  Time.new    #=> Wed Apr 09 08:56:33 CDT 2003
  sleep 1.9   #=> 2
  Time.new    #=> Wed Apr 09 08:56:35 CDT 2003

Kernel#split[править]


 split([pattern [, limit]])    => array

Equivalent to $_.split(pattern, limit). See String#split.

Kernel#sprintf[править]


 format(format_string [, arguments...] )   => string
 sprintf(format_string [, arguments...] )  => string

Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:

 Flag     | Applies to   | Meaning
 ---------+--------------+-----------------------------------------
 space    | bdeEfgGiouxX | Leave a space at the start of
          |              | positive numbers.
 ---------+--------------+-----------------------------------------
 (digit)$ | all          | Specifies the absolute argument number
          |              | for this field. Absolute and relative
          |              | argument numbers cannot be mixed in a
          |              | sprintf string.
 ---------+--------------+-----------------------------------------
  #       | beEfgGoxX    | Use an alternative format. For the
          |              | conversions `o', `x', `X', and `b',
          |              | prefix the result with ``0, ``0x, ``0X,
          |              |  and ``0b, respectively. For `e',
          |              | `E', `f', `g', and 'G', force a decimal
          |              | point to be added, even if no digits follow.
          |              | For `g' and 'G', do not remove trailing zeros.
 ---------+--------------+-----------------------------------------
 +        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
 ---------+--------------+-----------------------------------------
 -        | all          | Left-justify the result of this conversion.
 ---------+--------------+-----------------------------------------
 0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
 ---------+--------------+-----------------------------------------
 *        | all          | Use the next argument as the field width.
          |              | If negative, left-justify the result. If the
          |              | asterisk is followed by a number and a dollar
          |              | sign, use the indicated argument as the width.

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field. For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.) The field types are:

   Field |  Conversion
   ------+--------------------------------------------------------------
     b   | Convert argument as a binary number.
     c   | Argument is the numeric code for a single character.
     d   | Convert argument as a decimal number.
     E   | Equivalent to `e', but uses an uppercase E to indicate
         | the exponent.
     e   | Convert floating point argument into exponential notation
         | with one digit before the decimal point. The precision
         | determines the number of fractional digits (defaulting to six).
     f   | Convert floating point argument as [-]ddd.ddd,
         |  where the precision determines the number of digits after
         | the decimal point.
     G   | Equivalent to `g', but use an uppercase `E' in exponent form.
     g   | Convert a floating point number using exponential form
         | if the exponent is less than -4 or greater than or
         | equal to the precision, or in d.dddd form otherwise.
     i   | Identical to `d'.
     o   | Convert argument as an octal number.
     p   | The valuing of argument.inspect.
     s   | Argument is a string to be substituted. If the format
         | sequence contains a precision, at most that many characters
         | will be copied.
     u   | Treat argument as an unsigned decimal number. Negative integers
         | are displayed as a 32 bit two's complement plus one for the
         | underlying architecture; that is, 2 ** 32 + n.  However, since
         | Ruby has no inherent limit on bits used to represent the
         | integer, this value is preceded by two dots (..) in order to
         | indicate a infinite number of leading sign bits.
     X   | Convert argument as a hexadecimal number using uppercase
         | letters. Negative numbers will be displayed with two
         | leading periods (representing an infinite string of
         | leading 'FF's.
     x   | Convert argument as a hexadecimal number.
         | Negative numbers will be displayed with two
         | leading periods (representing an infinite string of
         | leading 'ff's.

Examples:

  sprintf("%d %04x", 123, 123)               #=> "123 007b"
  sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
  sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
  sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
  sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
  sprintf("%u", -123)                        #=> "..4294967173"

Kernel#srand[править]


 srand(number=0)    => old_seed

Seeds the pseudorandom number generator to the value of number.to_i.abs. If number is omitted or zero, seeds the generator using a combination of the time, the process id, and a sequence number. (This is also the behavior if Kernel::rand is called without previously calling srand, but without the sequence.) By setting the seed to a known value, scripts can be made deterministic during testing. The previous seed value is returned. Also see Kernel::rand.

Kernel#sub[править]


 sub(pattern, replacement)   => $_
 sub(pattern) { block }      => $_

Equivalent to $_.sub(args), except that $_ will be updated if substitution occurs.

Kernel#sub![править]


 sub!(pattern, replacement)    => $_ or nil
 sub!(pattern) {|...| block }  => $_ or nil

Equivalent to $_.sub!(args).

Kernel#syscall[править]


 syscall(fixnum [, args...])   => integer

Calls the operating system function identified by fixnum, passing in the arguments, which must be either String objects, or Integer objects that ultimately fit within a native long. Up to nine parameters may be passed (14 on the Atari-ST). The function identified by fixnum is system dependent. On some Unix systems, the numbers may be obtained from a header file called syscall.h.

  syscall 4, 1, "hello\n", 6   # '4' is write(2) on our box

produces:

  hello

Kernel#system[править]


 system(cmd [, arg, ...])    => true or false

Executes cmd in a subshell, returning true if the command was found and ran successfully, false otherwise. An error status is available in $?. The arguments are processed in the same way as for Kernel::exec.

  system("echo *")
  system("echo", "*")

produces:

  config.h main.rb
  *

Kernel#test[править]


 test(int_cmd, file1 [, file2] ) => obj

Uses the integer aCmd to perform various tests on
file1 (first table below) or on file1 and
file2 (second table).
File tests on a single file:
  Test   Returns   Meaning
   ?A  | Time    | Last access time for file1
   ?b  | boolean | True if file1 is a block device
   ?c  | boolean | True if file1 is a character device
   ?C  | Time    | Last change time for file1
   ?d  | boolean | True if file1 exists and is a directory
   ?e  | boolean | True if file1 exists
   ?f  | boolean | True if file1 exists and is a regular file
   ?g  | boolean | True if file1 has the \CF{setgid} bit
       |         | set (false under NT)
   ?G  | boolean | True if file1 exists and has a group
       |         | ownership equal to the caller's group
   ?k  | boolean | True if file1 exists and has the sticky bit set
   ?l  | boolean | True if file1 exists and is a symbolic link
   ?M  | Time    | Last modification time for file1
   ?o  | boolean | True if file1 exists and is owned by
       |         | the caller's effective uid
   ?O  | boolean | True if file1 exists and is owned by
       |         | the caller's real uid
   ?p  | boolean | True if file1 exists and is a fifo
   ?r  | boolean | True if file1 is readable by the effective
       |         | uid/gid of the caller
   ?R  | boolean | True if file is readable by the real
       |         | uid/gid of the caller
   ?s  | int/nil | If file1 has nonzero size, return the size,
       |         | otherwise return nil
   ?S  | boolean | True if file1 exists and is a socket
   ?u  | boolean | True if file1 has the setuid bit set
   ?w  | boolean | True if file1 exists and is writable by
       |         | the effective uid/gid
   ?W  | boolean | True if file1 exists and is writable by
       |         | the real uid/gid
   ?x  | boolean | True if file1 exists and is executable by
       |         | the effective uid/gid
   ?X  | boolean | True if file1 exists and is executable by
       |         | the real uid/gid
   ?z  | boolean | True if file1 exists and has a zero length

Tests that take two files:

   ?-  | boolean | True if file1 and file2 are identical
   ?=  | boolean | True if the modification times of file1
       |         | and file2 are equal
   ?<  | boolean | True if the modification time of file1
       |         | is prior to that of file2
   ?>  | boolean | True if the modification time of file1
       |         | is after that of file2

Kernel#throw[править]


 throw(symbol [, obj])

Transfers control to the end of the active catch block waiting for symbol. Raises NameError if there is no catch block for the symbol. The optional second parameter supplies a return value for the catch block, which otherwise defaults to nil. For examples, see Kernel::catch.

Kernel#to_ptr[править]


 to_ptr()

Allows arbitrary objects to be passed as a pointer to functions. (Probably not very GC safe, but by encapsulating it like this we can change the implementation later.)

Kernel#trace_var[править]


 trace_var(symbol, cmd )             => nil
 trace_var(symbol) {|val| block }    => nil

Controls tracing of assignments to global variables. The parameter +symbol_ identifies the variable (as either a string name or a symbol identifier). cmd (which may be a string or a Proc object) or block is executed whenever the variable is assigned. The block or Proc object receives the variable's new value as a parameter. Also see Kernel::untrace_var.

  trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
  $_ = "hello"
  $_ = ' there'

produces:

  $_ is now 'hello'
  $_ is now ' there'

Kernel#trap[править]


 Signal.trap( signal, proc ) => obj
 Signal.trap( signal ) {| | block } => obj

Specifies the handling of signals. The first parameter is a signal name (a string such as ``SIGALRM, ``SIGUSR1, and so on) or a signal number. The characters ``SIG may be omitted from the signal name. The command or block specifies code to be run when the signal is raised. If the command is the string ``IGNORE or ``SIG_IGN, the signal will be ignored. If the command is ``DEFAULT or ``SIG_DFL, the operating system's default handler will be invoked. If the command is ``EXIT, the script will be terminated by the signal. Otherwise, the given command or block will be run. The special signal name ``EXIT or signal number zero will be invoked just prior to program termination. trap returns the previous handler for the given signal.

   Signal.trap(0, proc { puts "Terminating: #{$$}" })
   Signal.trap("CLD")  { puts "Child died" }
   fork && Process.wait

produces:

   Terminating: 27461
   Child died
   Terminating: 27460

Kernel#untrace_var[править]


 untrace_var(symbol [, cmd] )   => array or nil

Removes tracing for the specified command on the given global variable and returns nil. If no command is specified, removes all tracing for that variable and returns an array containing the commands actually removed.

Kernel#warn[править]


 warn(msg)

(нет описания...)

Kernel#y[править]


 y( object, *objects )

Prints any supplied objects out in YAML. Intended as a variation on +Kernel::p+.

 S = Struct.new(:name, :state)
 s = S['dave', 'TX']
 y s

_produces:_

 --- !ruby/struct:S
 name: dave
 state: TX

Примесь Math[править]

Примесь Math содержит методы вычисления простейших тригонометрических и трансцендентных функций. Смотри список констант в классе Float, чтобы определить погрешность для чисел с плавающей точкой.


Константы

E, PI

Методы класса

acosh, acos, asinh, asin, atan2, atanh, atan, cosh, cos, erfc, erf, exp, frexp, hypot, ldexp, log10, log, sinh, sin, sqrt, tanh, tan

Math::acos[править]


Math.acos(x)    #-> float

Вычисляет арккосинус числа x. Возвращает значения в диапазоне 0..PI.

Math::acosh[править]


Math.acosh(x)    #-> float

Вычисляет значение обратной функции для гиперболического косинуса числа x.

Math::asin[править]


Math.asin(x)    #-> float

Вычисляет арксинус числа x. Возвращает значения в диапазоне 0..PI.

Math::asinh[править]


Math.asinh(x)    #-> float

Вычисляет значение обратной функции для гиперболического синуса числа x.

Math::atan[править]


Math.atan(x)    #-> float

Вычисляет арктангенс числа x. Возвращает значения в диапазоне -{PI/2} .. {PI/2}.

Math::atan2[править]


Math.atan2(y, x)  #-> float

Вычисляет арктангенс отношения, заданного числами y и x. Возвращает значения в диапазоне -PI..PI.

Math::atanh[править]


Math.atanh(x)    #-> float

Вычисляет значение обратной функции гиперболического тангенса числа x.

Math::cos[править]


Math.cos(x)    #-> float

Вычисляет косинус угла x (заданного в радианах). Возвращает значения в диапазоне -1..1.

Math::cosh[править]


Math.cosh(x)    #-> float

Вычисляет гиперболический косинус угла x (заданного в радианах).

Math::erf[править]


Math.erf(x)  #-> float

Вычисляет функцию ошибок x.

Math::erfc[править]


Math.erfc(x)  #-> float

Вычисляет дополнительную функцию ошибок x.

Math::exp[править]


Math.exp(x)    #-> float

Возвращает e**x (экспоненту числа х).

Math::frexp[править]


Math.frexp(numeric)    #-> [ fraction, exponent ]

Представляет число numeric в виде приведенного дробного числа (типа Float) и экспоненты (типа Fixnum). Возвращает массив из двух элементов, где первый элемент — дробное число, а второй — экспонента.

fraction, exponent = Math.frexp(1234)   #-> [0.6025390625, 11]
fraction * 2**exponent                  #-> 1234.0

Math::hypot[править]


Math.hypot(x, y)    #-> float

Возвращает sqrt(x**2 + y**2), то есть гипотенузу прямоугольного треугольника с катетами x и y.

Math.hypot(3, 4)   #-> 5.0

Math::ldexp[править]


Math.ldexp(flt, int) #-> float

Возвращает результат выражения flt*(2**int).

fraction, exponent = Math.frexp(1234)
Math.ldexp(fraction, exponent)   #-> 1234.0

Math::log[править]


Math.log(numeric)    #-> float

Возвращает натуральный логарифм числа numeric.

Math::log10[править]


Math.log10(numeric)    #-> float

Возвращает десятичный логарифм числа numeric.

Math::sin[править]


Math.sin(x)    #-> float

Вычисляет синус угла x (заданного в радианах). Returns -1..1.

Math::sinh[править]


Math.sinh(x)    #-> float

Вычисляет гиперболический синус угла x (заданного в радианах).

Math::sqrt[править]


Math.sqrt(numeric)    #-> float

Извлекает квадратный корень из неотрицательного числа numeric.

Math::tan[править]


Math.tan(x)    #-> float

Вычисляет тангенс угла x (заданного в радианах).

Math::tanh[править]


Math.tanh()    #-> float

Вычисляет гиперболический тангенс угла x (заданного в радианах).

Класс Module[править]

Module является коллекцией из методов и констант. Методы в модуле могут быть методами экземпляра или методами модуля. Метод экземпляра появляется как метод в классе, когда модуль подключен директивой include, методы модуля не выполняются. Напротив, методы модуля могут быть вызваны без создания инкапсулирующего объекта, в то время как методы экземпляра не могут. (См. Module#module_function)

В описании ниже, под параметром syml будем понимать символ, который является строкой в кавычках или объектом класса Symbol (таким, как, например, :name).

  module Mod
    include Math
    CONST = 1
    def meth
      #  ...
    end
  end
  Mod.class              #=> Module
  Mod.constants          #=> ["E", "PI", "CONST"]
  Mod.instance_methods   #=> ["meth"]

Extends the module object with module and instance accessors for class attributes, just like the native attr* accessors for instance attributes.


Also, modules included into Object need to be scanned and have their instance methods removed from blank slate. In theory, modules included into Kernel would have to be removed as well, but a "feature" of Ruby prevents late includes into modules from being exposed in the first place.


Методы класса

constants, nesting, new

Методы объекта

<=>, <=, <, ===, ==, >=, >, alias_method, ancestors, append_features, attr_accessor, attr_reader, attr_writer, attr, autoload?, autoload, class_eval, class_variable_get, class_variable_set, class_variables, const_defined?, const_get, const_missing, const_set, constants, define_method, extend_object, extended, freeze, include?, included_modules, included, include, instance_methods, instance_method, method_added, method_defined?, method_removed, method_undefined, module_eval, module_function, name, private_class_method, private_instance_methods, private_method_defined?, private, protected_instance_methods, protected_method_defined?, protected, public_class_method, public_instance_methods, public_method_defined?, public, remove_class_variable, remove_const, remove_method, to_s, undef_method

Module::constants[править]


 Module.constants   => array

Returns an array of the names of all constants defined in the system. This list includes the names of all modules and classes.

  p Module.constants.sort[1..5]

produces:

  ["ARGV", "ArgumentError", "Array", "Bignum", "Binding"]

Module::nesting[править]


 Module.nesting    => array

Returns the list of Modules nested at the point of call.

  module M1
    module M2
      $a = Module.nesting
    end
  end
  $a           #=> [M1::M2, M1]
  $a[0].name   #=> "M1::M2"

Module::new[править]


 Module.new                  => mod
 Module.new {|mod| block }   => mod

Creates a new anonymous module. If a block is given, it is passed the module object, and the block is evaluated in the context of this module using module_eval.

  Fred = Module.new do
    def meth1
      "hello"
    end
    def meth2
      "bye"
    end
  end
  a = "my string"
  a.extend(Fred)   #=> "my string"
  a.meth1          #=> "hello"
  a.meth2          #=> "bye"

Module#<[править]


 mod < other   =>  true, false, or nil

Returns true if mod is a subclass of other. Returns nil if there's no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "A<B").

Module#<=[править]


 mod <= other   =>  true, false, or nil

Returns true if mod is a subclass of other or is the same as other. Returns nil if there's no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "A<B").

Module#<=>[править]


 mod <=> other_mod   => -1, 0, +1, or nil

Comparison---Returns -1 if mod includes other_mod, 0 if mod is the same as other_mod, and +1 if mod is included by other_mod or if mod has no relationship with other_mod. Returns nil if other_mod is not a module.

Module#==[править]


 obj == other        => true or false
 obj.equal?(other)   => true or false
 obj.eql?(other)     => true or false

Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning. Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

  1 == 1.0     #=> true
  1.eql? 1.0   #=> false

Module#===[править]


 mod === obj    => true or false

Case Equality---Returns true if anObject is an instance of mod or one of mod's descendents. Of limited use for modules, but can be used in case statements to classify objects by class.

Module#>[править]


 mod > other   =>  true, false, or nil

Returns true if mod is an ancestor of other. Returns nil if there's no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "B>A").

Module#>=[править]


 mod >= other   =>  true, false, or nil

Returns true if mod is an ancestor of other, or the two modules are the same. Returns nil if there's no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "B>A").

Module#alias_method[править]


 alias_method(new_name, old_name)   => self

Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden.

  module Mod
    alias_method :orig_exit, :exit
    def exit(code=0)
      puts "Exiting with code #{code}"
      orig_exit(code)
    end
  end
  include Mod
  exit(99)

produces:

  Exiting with code 99

Module#ancestors[править]


 mod.ancestors -> array

Returns a list of modules included in mod (including mod itself).

  module Mod
    include Math
    include Comparable
  end
  Mod.ancestors    #=> [Mod, Comparable, Math]
  Math.ancestors   #=> [Math]

Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

Module#append_features, Module#append_features===Module#attr===


 attr(symbol, writable=false)    => nil

Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. If the optional writable argument is true, also creates a method called name= to set the attribute.

  module Mod
    attr  :size, true
  end

is equivalent to:

  module Mod
    def size
      @size
    end
    def size=(val)
      @size = val
    end
  end

Module#attr_accessor[править]


 attr_accessor(symbol, ...)    => nil

Equivalent to calling ``attrsymbol, true on each symbol in turn.

  module Mod
    attr_accessor(:one, :two)
  end
  Mod.instance_methods.sort   #=> ["one", "one=", "two", "two="]

Module#attr_reader[править]


 attr_reader(symbol, ...)    => nil

Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling ``attr:name on each name in turn.

Module#attr_writer[править]


 attr_writer(symbol, ...)    => nil

Creates an accessor method to allow assignment to the attribute aSymbol.id2name.

Module#autoload[править]


 mod.autoload(name, filename)   => nil

Registers filename to be loaded (using Kernel::require) the first time that name (which may be a String or a symbol) is accessed in the namespace of mod.

  module A
  end
  A.autoload(:B, "b")
  A::B.doit            # autoloads "b"

Module#autoload?[править]


 mod.autoload?(name)   => String or nil

Returns filename to be loaded if name is registered as autoload in the namespace of mod.

  module A
  end
  A.autoload(:B, "b")
  A.autoload?(:B)            # => "b"

Module#class_eval[править]


 mod.class_eval(string [, filename [, lineno]])  => obj
 mod.module_eval {|| block }                     => obj

Evaluates the string or block in the context of mod. This can be used to add methods to a class. module_eval returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.

  class Thing
  end
  a = %q{def hello() "Hello there!" end}
  Thing.module_eval(a)
  puts Thing.new.hello()
  Thing.module_eval("invalid code", "dummy", 123)

produces:

  Hello there!
  dummy:123:in `module_eval': undefined local variable
      or method `code' for Thing:Class

Module#class_variable_get[править]


 mod.class_variable_get(symbol)    => obj

Returns the value of the given class variable (or throws a NameError exception). The @@ part of the variable name should be included for regular class variables

  class Fred
    @@foo = 99
  end
  def Fred.foo
    class_variable_get(:@@foo)     #=> 99
  end

Module#class_variable_set[править]


 obj.class_variable_set(symbol, obj)    => obj

Sets the class variable names by symbol to object.

  class Fred
    @@foo = 99
    def foo
      @@foo
    end
  end
  def Fred.foo
    class_variable_set(:@@foo, 101)      #=> 101
  end
  Fred.foo
  Fred.new.foo                             #=> 101

Module#class_variables[править]


 mod.class_variables   => array

Returns an array of the names of class variables in mod and the ancestors of mod.

  class One
    @@var1 = 1
  end
  class Two < One
    @@var2 = 2
  end
  One.class_variables   #=> ["@@var1"]
  Two.class_variables   #=> ["@@var2", "@@var1"]

Module#const_defined?[править]


 mod.const_defined?(sym)   => true or false

Returns true if a constant with the given name is defined by mod.

  Math.const_defined? "PI"   #=> true

Module#const_get[править]


 mod.const_get(sym)    => obj

Returns the value of the named constant in mod.

  Math.const_get(:PI)   #=> 3.14159265358979

Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

Module#const_missing, Module#const_missing===Module#const_set===


 mod.const_set(sym, obj)    => obj

Sets the named constant to the given object, returning that object. Creates a new constant if no constant with the given name previously existed.

  Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0)   #=> 3.14285714285714
  Math::HIGH_SCHOOL_PI - Math::PI              #=> 0.00126448926734968

Module#constants[править]


 mod.constants    => array

Returns an array of the names of the constants accessible in mod. This includes the names of constants in any included modules (example at start of section).

Module#define_method[править]


 define_method(symbol, method)     => new_method
 define_method(symbol) { block }   => proc

Defines an instance method in the receiver. The method parameter can be a Proc or Method object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval, a point that is tricky to demonstrate because define_method is private. (This is why we resort to the send hack in this example.)

  class A
    def fred
      puts "In Fred"
    end
    def create_method(name, &block)
      self.class.send(:define_method, name, &block)
    end
    define_method(:wilma) { puts "Charge it!" }
  end
  class B < A
    define_method(:barney, instance_method(:fred))
  end
  a = B.new
  a.barney
  a.wilma
  a.create_method(:betty) { p self }
  a.betty

produces:

  In Fred
  Charge it!
  #<B:0x401b39e8>

Module#extend_object[править]


 extend_object(obj)    => obj

Extends the specified object by adding this module's constants and methods (which are added as singleton methods). This is the callback method used by Object#extend.

  module Picky
    def Picky.extend_object(o)
      if String === o
        puts "Can't add Picky to a String"
      else
        puts "Picky added to #{o.class}"
        super
      end
    end
  end
  (s = Array.new).extend Picky  # Call Object.extend
  (s = "quick brown fox").extend Picky

produces:

  Picky added to Array
  Can't add Picky to a String

Module#extended[править]


 extended(p1)

Not documented

Module#freeze[править]


 mod.freeze

Prevents further modifications to mod.

Module#include[править]


 include(module, ...)    => self

Invokes Module.append_features on each parameter in turn.

Module#include?[править]


 mod.include?(module)    => true or false

Returns true if module is included in mod or one of mod's ancestors.

  module A
  end
  class B
    include A
  end
  class C < B
  end
  B.include?(A)   #=> true
  C.include?(A)   #=> true
  A.include?(A)   #=> false

Module#included[править]


 included( othermod )

Callback invoked whenever the receiver is included in another module or class. This should be used in preference to Module.append_features if your code wants to perform some action when a module is included in another.

      module A
        def A.included(mod)
          puts "#{self} included in #{mod}"
        end
      end
      module Enumerable
        include A
      end

Module#included_modules[править]


 mod.included_modules -> array

Returns the list of modules included in mod.

  module Mixin
  end
  module Outer
    include Mixin
  end
  Mixin.included_modules   #=> []
  Outer.included_modules   #=> [Mixin]

Module#instance_method[править]


 mod.instance_method(symbol)   => unbound_method

Returns an UnboundMethod representing the given instance method in mod.

  class Interpreter
    def do_a() print "there, "; end
    def do_d() print "Hello ";  end
    def do_e() print "!\n";     end
    def do_v() print "Dave";    end
    Dispatcher = {
     ?a => instance_method(:do_a),
     ?d => instance_method(:do_d),
     ?e => instance_method(:do_e),
     ?v => instance_method(:do_v)
    }
    def interpret(string)
      string.each_char {|b| Dispatcher[b].bind(self).call }
    end
  end
  interpreter = Interpreter.new
  interpreter.interpret('dave')

produces:

  Hello there, Dave!

Module#instance_methods[править]


 mod.instance_methods(include_super=true)   => array

Returns an array containing the names of public instance methods in the receiver. For a module, these are the public methods; for a class, they are the instance (not singleton) methods. With no argument, or with an argument that is false, the instance methods in mod are returned, otherwise the methods in mod and mod's superclasses are returned.

  module A
    def method1()  end
  end
  class B
    def method2()  end
  end
  class C < B
    def method3()  end
  end
  A.instance_methods                #=> ["method1"]
  B.instance_methods(false)         #=> ["method2"]
  C.instance_methods(false)         #=> ["method3"]
  C.instance_methods(true).length   #=> 43

Module#method_added[править]


 method_added(p1)

Not documented

Module#method_defined?[править]


 mod.method_defined?(symbol)    => true or false

Returns true if the named method is defined by mod (or its included modules and, if mod is a class, its ancestors). Public and protected methods are matched.

  module A
    def method1()  end
  end
  class B
    def method2()  end
  end
  class C < B
    include A
    def method3()  end
  end
  A.method_defined? :method1    #=> true
  C.method_defined? "method1"   #=> true
  C.method_defined? "method2"   #=> true
  C.method_defined? "method3"   #=> true
  C.method_defined? "method4"   #=> false

Module#method_removed[править]


 method_removed(p1)

Not documented

Module#method_undefined[править]


 method_undefined(p1)

Not documented

Module#module_eval[править]


 mod.class_eval(string [, filename [, lineno]])  => obj
 mod.module_eval {|| block }                     => obj

Evaluates the string or block in the context of mod. This can be used to add methods to a class. module_eval returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.

  class Thing
  end
  a = %q{def hello() "Hello there!" end}
  Thing.module_eval(a)
  puts Thing.new.hello()
  Thing.module_eval("invalid code", "dummy", 123)

produces:

  Hello there!
  dummy:123:in `module_eval': undefined local variable
      or method `code' for Thing:Class

Module#module_function[править]


 module_function(symbol, ...)    => self

Creates module functions for the named methods. These functions may be called with the module as a receiver, and also become available as instance methods to classes that mix in the module. Module functions are copies of the original, and so may be changed independently. The instance-method versions are made private. If used with no arguments, subsequently defined methods become module functions.

  module Mod
    def one
      "This is one"
    end
    module_function :one
  end
  class Cls
    include Mod
    def callOne
      one
    end
  end
  Mod.one     #=> "This is one"
  c = Cls.new
  c.callOne   #=> "This is one"
  module Mod
    def one
      "This is the new one"
    end
  end
  Mod.one     #=> "This is one"
  c.callOne   #=> "This is the new one"

Module#name[править]


 mod.name    => string

Returns the name of the module mod.

Module#private[править]


 private                 => self
 private(symbol, ...)    => self

With no arguments, sets the default visibility for subsequently defined methods to private. With arguments, sets the named methods to have private visibility.

  module Mod
    def a()  end
    def b()  end
    private
    def c()  end
    private :a
  end
  Mod.private_instance_methods   #=> ["a", "c"]

Module#private_class_method[править]


 mod.private_class_method(symbol, ...)   => mod

Makes existing class methods private. Often used to hide the default constructor new.

  class SimpleSingleton  # Not thread safe
    private_class_method :new
    def SimpleSingleton.create(*args, &block)
      @me = new(*args, &block) if ! @me
      @me
    end
  end

Module#private_instance_methods[править]


 mod.private_instance_methods(include_super=true)    => array

Returns a list of the private instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.

  module Mod
    def method1()  end
    private :method1
    def method2()  end
  end
  Mod.instance_methods           #=> ["method2"]
  Mod.private_instance_methods   #=> ["method1"]

Module#private_method_defined?[править]


 mod.private_method_defined?(symbol)    => true or false

Returns true if the named private method is defined by _ mod_ (or its included modules and, if mod is a class, its ancestors).

  module A
    def method1()  end
  end
  class B
    private
    def method2()  end
  end
  class C < B
    include A
    def method3()  end
  end
  A.method_defined? :method1            #=> true
  C.private_method_defined? "method1"   #=> false
  C.private_method_defined? "method2"   #=> true
  C.method_defined? "method2"           #=> false

Module#protected[править]


 protected                => self
 protected(symbol, ...)   => self

With no arguments, sets the default visibility for subsequently defined methods to protected. With arguments, sets the named methods to have protected visibility.

Module#protected_instance_methods[править]


 mod.protected_instance_methods(include_super=true)   => array

Returns a list of the protected instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.

Module#protected_method_defined?[править]


 mod.protected_method_defined?(symbol)   => true or false

Returns true if the named protected method is defined by mod (or its included modules and, if mod is a class, its ancestors).

  module A
    def method1()  end
  end
  class B
    protected
    def method2()  end
  end
  class C < B
    include A
    def method3()  end
  end
  A.method_defined? :method1              #=> true
  C.protected_method_defined? "method1"   #=> false
  C.protected_method_defined? "method2"   #=> true
  C.method_defined? "method2"             #=> true

Module#public[править]


 public                 => self
 public(symbol, ...)    => self

With no arguments, sets the default visibility for subsequently defined methods to public. With arguments, sets the named methods to have public visibility.

Module#public_class_method[править]


 mod.public_class_method(symbol, ...)    => mod

Makes a list of existing class methods public.

Module#public_instance_methods[править]


 mod.public_instance_methods(include_super=true)   => array

Returns a list of the public instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.

Module#public_method_defined?[править]


 mod.public_method_defined?(symbol)   => true or false

Returns true if the named public method is defined by mod (or its included modules and, if mod is a class, its ancestors).

  module A
    def method1()  end
  end
  class B
    protected
    def method2()  end
  end
  class C < B
    include A
    def method3()  end
  end
  A.method_defined? :method1           #=> true
  C.public_method_defined? "method1"   #=> true
  C.public_method_defined? "method2"   #=> false
  C.method_defined? "method2"          #=> true

Module#remove_class_variable[править]


 remove_class_variable(sym)    => obj

Removes the definition of the sym, returning that constant's value.

  class Dummy
    @@var = 99
    puts @@var
    remove_class_variable(:@@var)
    puts(defined? @@var)
  end

produces:

  99
  nil

Module#remove_const[править]


 remove_const(sym)   => obj

Removes the definition of the given constant, returning that constant's value. Predefined classes and singleton objects (such as true) cannot be removed.

Module#remove_method[править]


 remove_method(symbol)   => self

Removes the method identified by symbol from the current class. For an example, see Module.undef_method.

Module#to_s[править]


 mod.to_s   => string

Return a string representing this module or class. For basic classes and modules, this is the name. For singletons, we show information on the thing we're attached to as well.

Module#undef_method[править]


 undef_method(symbol)    => self

Prevents the current class from responding to calls to the named method. Contrast this with remove_method, which deletes the method from the particular class; Ruby will still search superclasses and mixed-in modules for a possible receiver.

  class Parent
    def hello
      puts "In parent"
    end
  end
  class Child < Parent
    def hello
      puts "In child"
    end
  end
  c = Child.new
  c.hello
  class Child
    remove_method :hello  # remove from child, still in parent
  end
  c.hello
  class Child
    undef_method :hello   # prevent any calls to 'hello'
  end
  c.hello

produces:

  In child
  In parent
  prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError)

Класс NilClass[править]

Глобальное значение nil является единственным экземпляром класса NilClass и означает «отсутствие значения». В логическом контексте эквивалентно false. Методы, которые хотят сказать, что им нечего вернуть — возвращают nil. Переменные, значение которым не присвоено — имеют значение nil.


Методы объекта

&, ^, inspect, nil?, to_a, to_f, to_i, to_s, ||

NilClass#&[править]


false & obj   #-> false
nil & obj     #-> false

Логическое «И» всегда возвращает false. obj всегда вычисляется, так как является агрументом метода. В этом случае нет никакого сокращенного вычисления.

NilClass#^[править]


false ^ obj    #-> true или false
nil   ^ obj    #-> true или false

Логическое «ИЛИ НЕ». Если obj равен nil или false, возвращает false; иначе возвращает true.

NilClass#inspect[править]


nil.inspect  #-> "nil"

Всегда возвращает строку "nil".

NilClass#nil?[править]


nil.nil?   #-> true

Всегда возвращает true.

NilClass#to_a[править]


nil.to_a    #-> []

Всегда возвращает пустой массив.

NilClass#to_f[править]


nil.to_f    #-> 0.0

Всегда возвращает нуль.

NilClass#to_i[править]


nil.to_i    #-> 0

Всегда возвращает нуль.

NilClass#to_s[править]


nil.to_s    #-> ""

Всегда возвращает пустую строку.

NilClass#|[править]


false | obj   #->   true или false
nil   | obj   #->   true или false

Логическое «ИЛИ» возвращает false, если obj равен nil или false; true иначе.

Класс Numeric[править]

Numeric — это базовый класс для всех видов чисел (Fixnum, Float и так далее). Его методы добавляются ко всем классам, которые отвечают за числа.


Примеси

Comparable (<, <=, ==, >, >=, between?)

Методы объекта

+@, -@, <=>, abs, ceil, coerce, divmod, div, eql?, floor, integer?, modulo, nonzero?, quo, remainder, round, singleton_method_added, step, to_int, truncate, zero?

Numeric#+@[править]


+num    #-> num

Унарный плюс — возвращает число num в качестве результата.

Numeric#-@[править]


-num    #-> numeric

Унарный минус — возвращает число num с противоположным знаком в качестве результата.

Numeric#<=>[править]


first <=> second #-> -1 или 0 или 1

Возвращает:

  • first > second #=> 1
  • first == second #=> 0
  • first < second #=> −1.

Numeric#abs[править]


num.abs   #-> num или numeric

Возвращает абсолютное значение («по модулю») числа num.

12.abs         #-> 12
(-34.56).abs   #-> 34.56
-34.56.abs     #-> 34.56

Numeric#ceil[править]


num.ceil    #-> integer

Возвращает наименьшее целое число, которое больше или равно num. Класс Numeric добивается этого конвертацией num в дробное число и вызова метода Float#ceil.

1.ceil        #-> 1
1.2.ceil      #-> 2
(-1.2).ceil   #-> -1
(-1.0).ceil   #-> -1
Информация

Полезно посмотреть на методы round, floor и truncate, которые имеют схожую функциональность

Numeric#coerce[править]


num.coerce(numeric)   #-> array

Если numeric такого же типа, что и num, то возвращает массив, состоящий из numeric и num. Иначе, возвращает массив с numeric и num преобразованных в дробные числа. Этот метод используется при обработке арифметических операций со смешанными типами.

1.coerce(2.5)   #-> [2.5, 1.0]
1.2.coerce(3)   #-> [3.0, 1.2]
1.coerce(2)     #-> [2, 1]

Numeric#div[править]


num.div(numeric)    #-> integer

Использует оператор / для выполнения деления числа num на число numeric, после чего конвертирует результат в целое число. В классе Numeric отсутствует оператор /; вызывается оператор, реализованный в его подклассах.

Numeric#divmod[править]


num.divmod( aNumeric ) #-> anArray

Возвращает массив, состоящий из результата целочисленного деления и остатка от деления числа num на число aNumeric. То есть, если

q, r = x.divmod(y)

тогда действительно следующее равенство

q = floor(float(x)/float(y))
x = q*y + r

Частное округляется в меньшую сторону, как показано в таблице:

a b a.divmod(b) a/b a.modulo(b) a.remainder(b)
13 4 [3, 1] 3 1 1
13 -4 [-4, -3] -3 -3 1
-13 4 [-4, 3] -4 3 -1
-13 -4 [3, -1] 3 -1 -1
11.5 4 [2, 3.5] 2.875 3.5 3.5
11.5 -4 [-3, -0.5] -2.875 -0.5 3.5
-11.5 4 [-3, 0.5] -2.875 0.5 -3.5
-11.5 -4 [2, -3.5] 2.875 -3.5 -3.5
11.divmod(3)         #-> [3, 2]
11.divmod(-3)        #-> [-4, -1]
11.divmod(3.5)       #-> [3, 0.5]
-11.divmod(3.5)      #-> [-4, 3.0]
11.5.divmod(3.5)     #-> [3, 1.0]
Информация

Полезно посмотреть на методы modulo и remainder, которые имеют схожую функциональность

Numeric#eql?[править]


num.eql?(numeric)    #-> true или false

Возвращает true, если num и numeric одного и того же типа и имеют одинаковые значения.

1 == 1.0          #-> true
1.eql?(1.0)       #-> false
(1.0).eql?(1.0)   #-> true

Numeric#floor[править]


num.floor    #-> integer

Возвращает наибольшее целое число, которое меньше или равно num. Класс Numeric добивается этого конвертацией num в дробное число и вызова метода Float#floor.

0.3.floor               #-> 0
(-0.3).floor            #-> -1
(12345.54321).floor(3)  #-> 12345.543
(12345.54321).floor(-3) #-> 12000
Информация

Полезно посмотреть на методы round, ceil и truncate, которые имеют схожую функциональность

Numeric#integer?[править]


num.integer? #-> true или false

Возвращает true, если num является целым числом.

Numeric#modulo[править]


num.modulo(numeric)    #-> result

Получение остатка от деления числа num на число numeric. Эквивалентен вызову num.divmod(numeric)[1].

Информация

Полезно посмотреть на методы divmod и remainder, которые имеют схожую функциональность

Numeric#nonzero?[править]


num.nonzero?    #-> num или nil

Возвращает num, если num не является нулем, если num это ноль, то возвращает nil. Данный метод обычно используется совместно с оператором сравнения:

a = %w( z Bb bB bb BB a aA Aa AA A )
b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
b   #-> ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]

Numeric#quo[править]


num.quo(numeric)    #->   result

Эквивалентен оператору /, но переопределяется в подклассах.

Numeric#remainder[править]


num.remainder(numeric)    #-> result

Если num и numeric имеют разные знаки, то возвращает разность mod-numeric; иначе, возвращает mod. Для обоих случаев mod вычисляется по формуле:

num.modulo(numeric)
Информация

Различия между remainder и modulo (%) можно посмотреть в таблице, которая прилагается к методу divmod

Numeric#round[править]


num.round    #-> integer

Округляет число num до ближайшего целого. Класс Numeric добивается этого конвертацией num в дробное число и вызова метода Float#round.

Информация

Полезно посмотреть на методы ceil, floor и truncate, которые имеют схожую функциональность

Numeric#singleton_method_added[править]


num.singleton_method_added( new_method )

Перехватывает попытки добавления метода к объекту класса Numeric (и его наследников). Всегда вызывает ошибку типа TypeError.

Numeric#step[править]


num.step(limit, step ) {|i| block }     #-> num

Выполняет блок для всех чисел с шагом step, начиная с num и заканчивая limit. Значение step может быть как положительное, так и отрицательное. Главное, чтобы значение step согласовывалось с значением limit (если step < 0, то limit должен быть меньше num). Если все аргументы метода — целые числа, то счетчик итератора (который передается параметром в блок), тоже будет целочисленным. Если хотя бы один из аргументов метода — дробный, то все остальные преобразуются в дробное число и блок выполняется floor(n + n*epsilon)+ 1 раз, где n = (limit - num)/step.

1.step(10, 2) { |i| print i, " " }
Math::E.step(Math::PI, 0.2) { |f| print f, " " }

результат:

 1 3 5 7 9
 2.71828182845905 2.91828182845905 3.11828182845905

Numeric#to_int[править]


num.to_int    #-> integer

Вызывает метод to_i (реализованный в подклассах) для преобразования num в целое число.

Numeric#truncate[править]


num.truncate    #-> integer

Возвращает целую часть числа num. Класс Numeric добивается этого конвертацией num в дробное число и вызова метода Float#trancate.

Информация

Полезно посмотреть на методы round, floor и ceil, которые имеют схожую функциональность

Numeric#zero?[править]


num.zero?    #-> true или false

Возвращает true, если num равен нулю.

Класс Object[править]

Object is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden. Object mixes in the Kernel module, making the built-in kernel functions globally accessible. Although the instance methods of Object are defined by the Kernel module, we have chosen to document them here for clarity. In the descriptions of Object's methods, the parameter symbol refers to a symbol, which is either a quoted string or a Symbol (such as :name).


Same as above, except in Object.


metaprogramming assistant -- metaid.rb


Примеси

Kernel (Array, Float, Integer, Pathname, String, URI, `, abort, at_exit, autoload, autoload?, binding, block_given?, callcc, caller, catch, chomp, chomp!, chop, chop!, eval, exec, exit, exit!, fail, fork, format, gem, getc, gets, global_variables, gsub, gsub!, iterator?, lambda, load, local_variables, loop, method_missing, open, open_uri_original_open, p, pp, pretty_inspect, print, printf, proc, putc, puts, raise, rake_dup, rand, readline, readlines, require, require_gem, scan, scanf, select, set_trace_func, sleep, split, sprintf, srand, sub, sub!, syscall, system, test, throw, to_ptr, trace_var, trap, untrace_var, warn, y),

PP::ObjectMixin (pretty_print, pretty_print_cycle, pretty_print_inspect, pretty_print_instance_variables)

Константы

ARGF, ARGV, DATA, ENV, FALSE, IPsocket, MatchingData, NIL, PLATFORM, RELEASE_DATE, RUBY_PATCHLEVEL, RUBY_PLATFORM, RUBY_RELEASE_DATE, RUBY_VERSION, SOCKSsocket, STDERR, STDIN, STDOUT, TCPserver, TCPsocket, TOPLEVEL_BINDING, TRUE, UDPsocket, UNIXserver, UNIXsocket, VERSION

Методы класса

find_hidden_method, method_added, new

Методы объекта

===, ==, =~, __id__, __send__, class_def, class, clone, dclone, display, dup, enum_for, eql?, equal?, extend, freeze, frozen?, hash, id, inspect, instance_eval, instance_of?, instance_variable_get, instance_variable_set, instance_variables, is_a?, kind_of?, meta_def, meta_eval, metaclass, methods, method, nil?, object_id, private_methods, protected_methods, public_methods, remove_instance_variable, respond_to?, send, singleton_method_added, singleton_method_removed, singleton_method_undefined, singleton_methods, tainted?, taint, to_a, to_enum, to_s, to_yaml_properties, to_yaml_style, to_yaml, type, untaint

Object::find_hidden_method[править]


 Object::find_hidden_method(name)

(нет описания...)

Object::method_added[править]


 Object::method_added(name)

Detect method additions to Object and remove them in the BlankSlate class.

Object::new[править]


 Object::new()

Not documented

Object#==[править]


 obj == other        => true or false
 obj.equal?(other)   => true or false
 obj.eql?(other)     => true or false

Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning. Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

  1 == 1.0     #=> true
  1.eql? 1.0   #=> false

Object#===[править]


 obj === other   => true or false

Case Equality---For class Object, effectively the same as calling #==, but typically overridden by descendents to provide meaningful semantics in case statements.

Object#=~[править]


 obj =~ other  => false

Pattern Match---Overridden by descendents (notably Regexp and String) to provide meaningful pattern-match semantics.

Object#__id__[править]


 obj.__id__       => fixnum
 obj.object_id    => fixnum

Document-method: object_id Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id.

Object#__send__[править]


 obj.send(symbol [, args...])        => obj
 obj.__send__(symbol [, args...])    => obj

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.

  class Klass
    def hello(*args)
      "Hello " + args.join(' ')
    end
  end
  k = Klass.new
  k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"

Object#class[править]


 obj.class    => class

Returns the class of obj, now preferred over Object#type, as an object's type in Ruby is only loosely tied to that object's class. This method must always be called with an explicit receiver, as class is also a reserved word in Ruby.

  1.class      #=> Fixnum
  self.class   #=> Object

Object#class_def[править]


 class_def(name, &blk)

Defines an instance method within a class

Object#clone[править]


 obj.clone -> an_object

Produces a shallow copy of obj---the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj. See also the discussion under Object#dup.

  class Klass
     attr_accessor :str
  end
  s1 = Klass.new      #=> #<Klass:0x401b3a38>
  s1.str = "Hello"    #=> "Hello"
  s2 = s1.clone       #=> #<Klass:0x401b3998 @str="Hello">
  s2.str[1,4] = "i"   #=> "i"
  s1.inspect          #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
  s2.inspect          #=> "#<Klass:0x401b3998 @str=\"Hi\">"

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

Object#dclone[править]


 dclone()

(нет описания...)

Object#display[править]


 obj.display(port=$>)    => nil

Prints obj on the given port (default $>). Equivalent to:

  def display(port=$>)
    port.write self
  end

For example:

  1.display
  "cat".display
  [ 4, 5, 6 ].display
  puts

produces:

  1cat456

Object#dup[править]


 obj.dup -> an_object

Produces a shallow copy of obj---the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, clone and dup may have different semantics in descendent classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendent object to create the new instance. This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

Object#enum_for[править]


 obj.to_enum(method = :each, *args)
 obj.enum_for(method = :each, *args)

Returns Enumerable::Enumerator.new(self, method, *args). e.g.:

  str = "xyz"
  enum = str.enum_for(:each_byte)
  a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]
  # protects an array from being modified
  a = [1, 2, 3]
  some_method(a.to_enum)

Object#eql?[править]


 obj == other        => true or false
 obj.equal?(other)   => true or false
 obj.eql?(other)     => true or false

Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning. Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

  1 == 1.0     #=> true
  1.eql? 1.0   #=> false

Object#equal?[править]


 obj == other        => true or false
 obj.equal?(other)   => true or false
 obj.eql?(other)     => true or false

Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning. Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

  1 == 1.0     #=> true
  1.eql? 1.0   #=> false

Object#extend[править]


 obj.extend(module, ...)    => obj

Adds to obj the instance methods from each module given as a parameter.

  module Mod
    def hello
      "Hello from Mod.\n"
    end
  end
  class Klass
    def hello
      "Hello from Klass.\n"
    end
  end
  k = Klass.new
  k.hello         #=> "Hello from Klass.\n"
  k.extend(Mod)   #=> #<Klass:0x401b3bc8>
  k.hello         #=> "Hello from Mod.\n"

Object#freeze[править]


 obj.freeze    => obj

Prevents further modifications to obj. A TypeError will be raised if modification is attempted. There is no way to unfreeze a frozen object. See also Object#frozen?.

  a = [ "a", "b", "c" ]
  a.freeze
  a << "z"

produces:

  prog.rb:3:in `<<': can't modify frozen array (TypeError)
   from prog.rb:3

Object#frozen?[править]


 obj.frozen?    => true or false

Returns the freeze status of obj.

  a = [ "a", "b", "c" ]
  a.freeze    #=> ["a", "b", "c"]
  a.frozen?   #=> true

Object#hash[править]


 obj.hash    => fixnum

Generates a Fixnum hash value for this object. This function must have the property that a.eql?(b) implies a.hash == b.hash. The hash value is used by class Hash. Any hash value that exceeds the capacity of a Fixnum will be truncated before being used.

Object#id[править]


 obj.id    => fixnum

Soon-to-be deprecated version of Object#object_id.

Object#inspect[править]


 obj.inspect   => string

Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string.

  [ 1, 2, 3..4, 'five' ].inspect   #=> "[1, 2, 3..4, \"five\"]"
  Time.new.inspect                 #=> "Wed Apr 09 08:54:39 CDT 2003"

Object#instance_eval[править]


 obj.instance_eval(string [, filename [, lineno]] )   => obj
 obj.instance_eval {| | block }                       => obj

Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj's instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.

  class Klass
    def initialize
      @secret = 99
    end
  end
  k = Klass.new
  k.instance_eval { @secret }   #=> 99

Object#instance_of?[править]


 obj.instance_of?(class)    => true or false

Returns true if obj is an instance of the given class. See also Object#kind_of?.

Object#instance_variable_get[править]


 instance_variable_get(ivarname)

(нет описания...)

Object#instance_variable_set[править]


 instance_variable_set(ivarname, value)

(нет описания...)

Object#instance_variables[править]


 obj.instance_variables    => array

Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable.

  class Fred
    attr_accessor :a1
    def initialize
      @iv = 3
    end
  end
  Fred.new.instance_variables   #=> ["@iv"]

Object#is_a?[править]


 obj.is_a?(class)       => true or false
 obj.kind_of?(class)    => true or false

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

  module M;    end
  class A
    include M
  end
  class B < A; end
  class C < B; end
  b = B.new
  b.instance_of? A   #=> false
  b.instance_of? B   #=> true
  b.instance_of? C   #=> false
  b.instance_of? M   #=> false
  b.kind_of? A       #=> true
  b.kind_of? B       #=> true
  b.kind_of? C       #=> false
  b.kind_of? M       #=> true

Object#kind_of?[править]


 obj.is_a?(class)       => true or false
 obj.kind_of?(class)    => true or false

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

  module M;    end
  class A
    include M
  end
  class B < A; end
  class C < B; end
  b = B.new
  b.instance_of? A   #=> false
  b.instance_of? B   #=> true
  b.instance_of? C   #=> false
  b.instance_of? M   #=> false
  b.kind_of? A       #=> true
  b.kind_of? B       #=> true
  b.kind_of? C       #=> false
  b.kind_of? M       #=> true

Object#meta_def[править]


 meta_def(name, &blk)

Adds methods to a metaclass

Object#meta_eval[править]


 meta_eval(&blk;)

(нет описания...)

Object#metaclass[править]


 metaclass()

The hidden singleton lurks behind everyone

Object#method[править]


 obj.method(sym)    => method

Looks up the named method as a receiver in obj, returning a Method object (or raising NameError). The Method object acts as a closure in obj's object instance, so instance variables and the value of self remain available.

  class Demo
    def initialize(n)
      @iv = n
    end
    def hello()
      "Hello, @iv = #{@iv}"
    end
  end
  k = Demo.new(99)
  m = k.method(:hello)
  m.call   #=> "Hello, @iv = 99"
  l = Demo.new('Fred')
  m = l.method("hello")
  m.call   #=> "Hello, @iv = Fred"

Object#methods[править]


 obj.methods    => array

Returns a list of the names of methods publicly accessible in obj. This will include all the methods accessible in obj's ancestors.

  class Klass
    def kMethod()
    end
  end
  k = Klass.new
  k.methods[0..9]    #=> ["kMethod", "freeze", "nil?", "is_a?",
                          "class", "instance_variable_set",
                           "methods", "extend", "send", "instance_eval"]
  k.methods.length   #=> 42

Object#nil?[править]


 nil?()

call_seq:

 nil.nil?               => true
 <anything_else>.nil?   => false

Only the object nil responds true to nil?.

Object#object_id[править]


 obj.__id__       => fixnum
 obj.object_id    => fixnum

Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. Object#object_id is a different concept from the :name notation, which returns the symbol id of name. Replaces the deprecated Object#id.

Object#private_methods[править]


 obj.private_methods(all=true)   => array

Returns the list of private methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

Object#protected_methods[править]


 obj.protected_methods(all=true)   => array

Returns the list of protected methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

Object#public_methods[править]


 obj.public_methods(all=true)   => array

Returns the list of public methods accessible to obj. If the all parameter is set to false, only those methods in the receiver will be listed.

Object#remove_instance_variable[править]


 obj.remove_instance_variable(symbol)    => obj

Removes the named instance variable from obj, returning that variable's value.

  class Dummy
    attr_reader :var
    def initialize
      @var = 99
    end
    def remove
      remove_instance_variable(:@var)
    end
  end
  d = Dummy.new
  d.var      #=> 99
  d.remove   #=> 99
  d.var      #=> nil

Object#respond_to?[править]


 obj.respond_to?(symbol, include_private=false) => true or false

Возвращает значение true, если объект отвечает на данный метод. Частные методы включены в поиск только тогда, когда необязательный второй параметр вычисляется как true.

Object#send[править]


 obj.send(symbol [, args...])        => obj
 obj.__send__(symbol [, args...])    => obj

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.

  class Klass
    def hello(*args)
      "Hello " + args.join(' ')
    end
  end
  k = Klass.new
  k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"

Object#singleton_method_added[править]


 singleton_method_added(symbol)

Invoked as a callback whenever a singleton method is added to the receiver.

  module Chatty
    def Chatty.singleton_method_added(id)
      puts "Adding #{id.id2name}"
    end
    def self.one()     end
    def two()          end
    def Chatty.three() end
  end

produces:

  Adding singleton_method_added
  Adding one
  Adding three

Object#singleton_method_removed[править]


 singleton_method_removed(symbol)

Invoked as a callback whenever a singleton method is removed from the receiver.

  module Chatty
    def Chatty.singleton_method_removed(id)
      puts "Removing #{id.id2name}"
    end
    def self.one()     end
    def two()          end
    def Chatty.three() end
    class <<self
      remove_method :three
      remove_method :one
    end
  end

produces:

  Removing three
  Removing one

Object#singleton_method_undefined[править]


 singleton_method_undefined(symbol)

Invoked as a callback whenever a singleton method is undefined in the receiver.

  module Chatty
    def Chatty.singleton_method_undefined(id)
      puts "Undefining #{id.id2name}"
    end
    def Chatty.one()   end
    class << self
       undef_method(:one)
    end
  end

produces:

  Undefining one

Object#singleton_methods[править]


 obj.singleton_methods(all=true)    => array

Returns an array of the names of singleton methods for obj. If the optional all parameter is true, the list will include methods in modules included in obj.

  module Other
    def three() end
  end
  class Single
    def Single.four() end
  end
  a = Single.new
  def a.one()
  end
  class << a
    include Other
    def two()
    end
  end
  Single.singleton_methods    #=> ["four"]
  a.singleton_methods(false)  #=> ["two", "one"]
  a.singleton_methods         #=> ["two", "one", "three"]

Object#taint[править]


 obj.taint -> obj

Marks obj as tainted---if the $SAFE level is set appropriately, many method calls which might alter the running programs environment will refuse to accept tainted strings.

Object#tainted?[править]


 obj.tainted?    => true or false

Returns true if the object is tainted.

Object#to_a[править]


 obj.to_a -> anArray

Returns an array representation of obj. For objects of class Object and others that don't explicitly override the method, the return value is an array containing self. However, this latter behavior will soon be obsolete.

  self.to_a       #=> -:1: warning: default `to_a' will be obsolete
  "hello".to_a    #=> ["hello"]
  Time.new.to_a   #=> [39, 54, 8, 9, 4, 2003, 3, 99, true, "CDT"]

Object#to_enum[править]


 obj.to_enum(method = :each, *args)
 obj.enum_for(method = :each, *args)

Returns Enumerable::Enumerator.new(self, method, *args). e.g.:

  str = "xyz"
  enum = str.enum_for(:each_byte)
  a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]
  # protects an array from being modified
  a = [1, 2, 3]
  some_method(a.to_enum)

Object#to_s[править]


 obj.to_s    => string

Returns a string representing obj. The default to_s prints the object's class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns ``main.

Object#type[править]


 obj.type   => class

Deprecated synonym for Object#class.

Object#untaint[править]


 obj.untaint    => obj

Removes the taint from obj.

Класс Proc[править]

Объекты Proc являются блоками кода, которые связаны с локальными переменными. Блок кода может быть выполнен в другом контексте.

def gen_times(factor)
  return Proc.new {|n| n*factor }
end

times3 = gen_times(3)
times5 = gen_times(5)

times3.call(12)               #-> 36
times5.call(5)                #-> 25
times3.call(times5.call(4))   #-> 60

Методы класса

new

Методы объекта

[], ==, arity, binding, call, clone, dup, to_proc, to_s

Proc::new[править]


Proc.new {|...| block } #-> a_proc 
Proc.new                #-> a_proc

Создает новый объект класса Proc и запоминает в нем текущий контекст. Proc::new может быть вызван без блока только в пределах метода к которому прицеплен блок (во время вызова). В этом случае блок будет преобразован в объект класса Proc.

def proc_from
  Proc.new
end
proc = proc_from { "hello" }
proc.call   #-> "hello"

Proc#==[править]


prc == other_proc   #->  true или false

Возвращает true, если prc и other_proc --- один и тот же объект, или если оба блока имеют одинаковое тело.

Proc#[][править]


prc.call(params,...)   #-> obj
prc[params,...]        #-> obj

Выполняет блок, присваивая параметрам блока значения params и остальных переменных, обозначенных троеточием. Выдает предупреждение, если блок ожидает лишь одно значение, а ему передается больше (тем не менее, он преобразует список параметров в массив и попытается выполнить блок). Для блоков, создаваемых с использованием Kernel.proc, генерируется ошибка если число параметров передаваемых в блок превышает число параметров объявленных во время его создания. Для блоков, созданных при помощи Proc.new, дополнительные параметры просто отбрасываются. Возвращает значение последнего вычисленного выражения в блоке. Смотри еще Proc#yield.

a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
a_proc.call(9, 1, 2, 3)   #-> [9, 18, 27]
a_proc[9, 1, 2, 3]        #-> [9, 18, 27]
a_proc = Proc.new {|a,b| a}
a_proc.call(1,2,3)

результат:

prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
 from prog.rb:4:in `call'
 from prog.rb:5

(еще известен как .call)

Proc#arity[править]


prc.arity   #-> fixnum

Возвращает количество аргументов, которые могут быть восприняты блоком. Если блок объявлен без указания аргументов, то возвращает 0. Если число агрументов точно равно n, то возвращает n. Если блок имеет оциональный аргумент, то возвращает -n-1, где n --- количество обязательных аргументов. Блок proc без аргументов обычно содержит || вместо аргументов.

Proc.new {}.arity          #->  0
Proc.new {||}.arity        #->  0
Proc.new {|a|}.arity       #->  1
Proc.new {|a,b|}.arity     #->  2
Proc.new {|a,b,c|}.arity   #->  3
Proc.new {|*a|}.arity      #-> -1
Proc.new {|a,*b|}.arity    #-> -2

Proc#binding[править]


prc.binding    #-> binding

Возвращает объект класса Binding ассоциированный с prc. Например, Kernel#eval принимает объекты Proc или Binding в качестве второго аргумента.

def fred(param)
  proc {}
end

b = fred(99)
eval("param", b.binding)   #-> 99
eval("param", b)           #-> 99

Proc#call[править]


prc.call(params,...)   #-> obj
prc[params,...]        #-> obj

Выполняет блок, присваивая параметрам блока значения params и остальных переменных, обозначенных троеточием. Выдает предупреждение, если блок ожидает лишь одно значение, а ему передается больше (тем не менее, он преобразует список параметров в массив и попытается выполнить блок). Для блоков, создаваемых с использованием Kernel.proc, генерируется ошибка если число параметров передаваемых в блок превышает число параметров объявленных во время его создания. Для блоков, созданных при помощи Proc.new, дополнительные параметры просто отбрасываются. Возвращает значение последнего вычисленного выражения в блоке. Смотри еще Proc#yield.

a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
a_proc.call(9, 1, 2, 3)   #-> [9, 18, 27]
a_proc[9, 1, 2, 3]        #-> [9, 18, 27]
a_proc = Proc.new {|a,b| a}
a_proc.call(1,2,3)

результат:

prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
 from prog.rb:4:in `call'
 from prog.rb:5

(еще известен как [])

Proc#clone[править]


prc.clone   #-> other_proc

Создает копию блока prc.

Proc#dup[править]


prc.dup   #-> other_proc

Создает копию блока prc.

Proc#to_proc[править]


prc.to_proc   #-> prc

Часть соглашения о преобразованиии других объектов в объекты класса Proc. Внутри класса Proc он просто возвращает сам себя.

Proc#to_s[править]


prc.to_s   #-> string

Возвращает строку с уникальным идентификатором для prc, вместе с указателем на место, где блок был объявлен.

Класс Process[править]

The Process module is a collection of methods used to manipulate processes.


Примеси

Windows::Console (AddConsoleAlias, AllocConsole, AttachConsole, CreateConsoleScreenBuffer, FillConsoleOutputAttribute, FlushConsoleInputBuffer, FreeConsole, GenerateConsoleCtrlEvent, GetConsoleAliasExes, GetConsoleAliasExesLength, GetConsoleAliases, GetConsoleAliasesLength, GetConsoleCP, GetConsoleCursorInfo, GetConsoleDisplayMode, GetConsoleFontSize, GetConsoleMode, GetConsoleOutputCP, GetConsoleProcessList, GetConsoleScreenBufferInfo, GetConsoleSelectionInfo, GetConsoleTitle, GetConsoleWindow, GetCurrentConsoleFont, GetLargestConsoleWindowSize, GetNumberOfConsoleInputEvents, GetNumberOfConsoleMouseButtons, GetStdHandle, PeekConsoleInput, ReadConsole, ReadConsoleInput, ReadConsoleOutput, ReadConsoleOutputAttribute, ReadConsoleOutputCharacter, ScrollConsoleScreenBuffer, SetConsoleActiveScreenBuffer, SetConsoleCP, SetConsoleCommandHistoryMode, SetConsoleCtrlHandler, SetConsoleCursorInfo, SetConsoleCursorPosition, SetConsoleDisplayMode, SetConsoleHistoryInfo, SetConsoleMode, SetConsoleOutputCP, SetConsoleScreenBufferSize, SetConsoleTextAttribute, SetConsoleTitle, SetConsoleWindowInfo, SetStdHandle, WriteConsole, WriteConsoleInput, WriteConsoleOutput, WriteConsoleOutputAttribute, WriteConsoleOutputCharacter),

Windows::Error (FormatMessage, FormatMessageW, GetLastError, SetErrorMode, SetLastError, SetLastErrorEx, get_last_error),

Windows::Handle (CloseHandle, DuplicateHandle, GetHandleInformation, SetHandleInformation, get_osfhandle, open_osfhandle),

Windows::Library (DisableThreadLibraryCalls, FreeLibrary, GetDllDirectory, GetModuleFileName, GetModuleHandle, GetModuleHandleEx, GetProcAddress, LoadLibrary, LoadLibraryEx, LoadModule, SetDllDirectory),

Windows::Process (CreateProcess, CreateRemoteThread, CreateThread, ExitProcess, GetCommandLine, GetCurrentProcess, GetCurrentProcessId, GetEnvironmentStrings, GetEnvironmentVariable, GetExitCodeProcess, GetPriorityClass, GetProcessHandleCount, GetProcessId, GetProcessTimes, GetStartupInfo, OpenProcess, SetEnvironmentVariable, Sleep, SleepEx, TerminateProcess, WaitForInputIdle),

Windows::Synchronize (CreateEvent, CreateMutex, CreateSemaphore, GetOverlappedResult, MsgWaitForMultipleObjects, MsgWaitForMultipleObjectsEx, OpenEvent, OpenMutex, OpenSemaphore, ReleaseMutex, ReleaseSemaphore, ResetEvent, SetEvent, WaitForMultipleObjects, WaitForMultipleObjectsEx, WaitForSingleObject, WaitForSingleObjectEx),

Windows::Window (GetClientRect, GetForegroundWindow, GetWindowRect)

Константы

PRIO_PGRP, PRIO_PROCESS, PRIO_USER, ProcessInfo, RLIMIT_AS, RLIMIT_CORE, RLIMIT_CPU, RLIMIT_DATA, RLIMIT_FSIZE, RLIMIT_MEMLOCK, RLIMIT_NOFILE, RLIMIT_NPROC, RLIMIT_RSS, RLIMIT_SBSIZE, RLIMIT_STACK, RLIM_INFINITY, RLIM_SAVED_CUR, RLIM_SAVED_MAX, WIN32_PROCESS_VERSION, WNOHANG, WUNTRACED

Методы класса

abort, detach, egid=, egid, euid=, euid, exit!, exit, fork, getpgid, getpriority, getrlimit, gid=, gid, groups=, groups, initgroups, kill, maxgroups=, maxgroups, pid, ppid, setpgid, setpgrp, setpriority, setrlimit, setsid, times, uid=, uid, wait2, waitall, waitpid2, waitpid, wait

Методы объекта

create, fork, kill, wait2, waitpid2, waitpid, wait

Process::abort[править]


 abort
 Kernel::abort
 Process::abort

Terminate execution immediately, effectively by calling Kernel.exit(1). If msg is given, it is written to STDERR prior to terminating.

Process::detach[править]


 Process.detach(pid)   => thread

Some operating systems retain the status of terminated child processes until the parent collects that status (normally using some variant of wait(). If the parent never collects this status, the child stays around as a zombie process. Process::detach prevents this by setting up a separate Ruby thread whose sole job is to reap the status of the process pid when it terminates. Use detach only when you do not intent to explicitly wait for the child to terminate. detach only checks the status periodically (currently once each second). In this first example, we don't reap the first child process, so it appears as a zombie in the process status display.

  p1 = fork { sleep 0.1 }
  p2 = fork { sleep 0.2 }
  Process.waitpid(p2)
  sleep 2
  system("ps -ho pid,state -p #{p1}")

produces:

  27389 Z

In the next example, Process::detach is used to reap the child automatically.

  p1 = fork { sleep 0.1 }
  p2 = fork { sleep 0.2 }
  Process.detach(p1)
  Process.waitpid(p2)
  sleep 2
  system("ps -ho pid,state -p #{p1}")

(produces no output)

Process::egid[править]


 Process.egid          => fixnum
 Process::GID.eid      => fixnum
 Process::Sys.geteid   => fixnum

Returns the effective group ID for this process. Not available on all platforms.

  Process.egid   #=> 500

Process::egid=[править]


 Process.egid = fixnum   => fixnum

Sets the effective group ID for this process. Not available on all platforms.

Process::euid[править]


 Process.euid           => fixnum
 Process::UID.eid       => fixnum
 Process::Sys.geteuid   => fixnum

Returns the effective user ID for this process.

  Process.euid   #=> 501

Process::euid=[править]


 Process.euid= integer

Sets the effective user ID for this process. Not available on all platforms.

Process::exit[править]


 exit(integer=0)
 Kernel::exit(integer=0)
 Process::exit(integer=0)

Initiates the termination of the Ruby script by raising the SystemExit exception. This exception may be caught. The optional parameter is used to return a status code to the invoking environment.

  begin
    exit
    puts "never get here"
  rescue SystemExit
    puts "rescued a SystemExit exception"
  end
  puts "after begin block"

produces:

  rescued a SystemExit exception
  after begin block

Just prior to termination, Ruby executes any at_exit functions (see Kernel::at_exit) and runs any object finalizers (see ObjectSpace::define_finalizer).

  at_exit { puts "at_exit function" }
  ObjectSpace.define_finalizer("string",  proc { puts "in finalizer" })
  exit

produces:

  at_exit function
  in finalizer

Process::exit![править]


 Process.exit!(fixnum=-1)

Exits the process immediately. No exit handlers are run. fixnum is returned to the underlying system as the exit status.

  Process.exit!(0)

Process::fork[править]


 Kernel.fork  [{ block }]   => fixnum or nil
 Process.fork [{ block }]   => fixnum or nil

Creates a subprocess. If a block is specified, that block is run in the subprocess, and the subprocess terminates with a status of zero. Otherwise, the fork call returns twice, once in the parent, returning the process ID of the child, and once in the child, returning nil. The child process can exit using Kernel.exit! to avoid running any at_exit functions. The parent process should use Process.wait to collect the termination statuses of its children or use Process.detach to register disinterest in their status; otherwise, the operating system may accumulate zombie processes. The thread calling fork is the only thread in the created child process. fork doesn't copy other threads.

Process::getpgid[править]


 Process.getpgid(pid)   => integer

Returns the process group ID for the given process id. Not available on all platforms.

  Process.getpgid(Process.ppid())   #=> 25527

Process::getpriority[править]


 Process.getpriority(kind, integer)   => fixnum

Gets the scheduling priority for specified process, process group, or user. kind indicates the kind of entity to find: one of Process::PRIO_PGRP, Process::PRIO_USER, or Process::PRIO_PROCESS. integer is an id indicating the particular process, process group, or user (an id of 0 means current). Lower priorities are more favorable for scheduling. Not available on all platforms.

  Process.getpriority(Process::PRIO_USER, 0)      #=> 19
  Process.getpriority(Process::PRIO_PROCESS, 0)   #=> 19

Process::getrlimit[править]


 Process.getrlimit(resource)   => [cur_limit, max_limit]

Gets the resource limit of the process. cur_limit means current (soft) limit and max_limit means maximum (hard) limit. resource indicates the kind of resource to limit: such as Process::RLIMIT_CORE, Process::RLIMIT_CPU, etc. See Process.setrlimit for details. cur_limit and max_limit may be Process::RLIM_INFINITY, Process::RLIM_SAVED_MAX or Process::RLIM_SAVED_CUR. See Process.setrlimit and the system getrlimit(2) manual for details.

Process::gid[править]


 Process.gid           => fixnum
 Process::GID.rid      => fixnum
 Process::Sys.getgid   => fixnum

Returns the (real) group ID for this process.

  Process.gid   #=> 500

Process::gid=[править]


 Process.gid= fixnum   => fixnum

Sets the group ID for this process.

Process::groups[править]


 Process.groups   => array

Get an Array of the gids of groups in the supplemental group access list for this process.

  Process.groups   #=> [27, 6, 10, 11]

Process::groups=[править]


 Process.groups= array   => array

Set the supplemental group access list to the given Array of group IDs.

  Process.groups   #=> [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
  Process.groups = [27, 6, 10, 11]   #=> [27, 6, 10, 11]
  Process.groups   #=> [27, 6, 10, 11]

Process::initgroups[править]


 Process.initgroups(username, gid)   => array

Initializes the supplemental group access list by reading the system group database and using all groups of which the given user is a member. The group with the specified gid is also added to the list. Returns the resulting Array of the gids of all the groups in the supplementary group access list. Not available on all platforms.

  Process.groups   #=> [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
  Process.initgroups( "mgranger", 30 )   #=> [30, 6, 10, 11]
  Process.groups   #=> [30, 6, 10, 11]

Process::kill[править]


 Process.kill(signal, pid, ...)    => fixnum

Sends the given signal to the specified process id(s), or to the current process if pid is zero. signal may be an integer signal number or a POSIX signal name (either with or without a SIG prefix). If signal is negative (or starts with a minus sign), kills process groups instead of processes. Not all signals are available on all platforms.

  pid = fork do
     Signal.trap("HUP") { puts "Ouch!"; exit }
     # ... do some work ...
  end
  # ...
  Process.kill("HUP", pid)
  Process.wait

produces:

  Ouch!

Process::maxgroups[править]


 Process.maxgroups   => fixnum

Returns the maximum number of gids allowed in the supplemental group access list.

  Process.maxgroups   #=> 32

Process::maxgroups=[править]


 Process.maxgroups= fixnum   => fixnum

Sets the maximum number of gids allowed in the supplemental group access list.

Process::pid[править]


 Process.pid   => fixnum

Returns the process id of this process. Not available on all platforms.

  Process.pid   #=> 27415

Process::ppid[править]


 Process.ppid   => fixnum

Returns the process id of the parent of this process. Always returns 0 on NT. Not available on all platforms.

  puts "I am #{Process.pid}"
  Process.fork { puts "Dad is #{Process.ppid}" }

produces:

  I am 27417
  Dad is 27417

Process::setpgid[править]


 Process.setpgid(pid, integer)   => 0

Sets the process group ID of pid (0 indicates this process) to integer. Not available on all platforms.

Process::setpgrp[править]


 Process.setpgrp   => 0

Equivalent to setpgid(0,0). Not available on all platforms.

Process::setpriority[править]


 Process.setpriority(kind, integer, priority)   => 0

See Process#getpriority.

  Process.setpriority(Process::PRIO_USER, 0, 19)      #=> 0
  Process.setpriority(Process::PRIO_PROCESS, 0, 19)   #=> 0
  Process.getpriority(Process::PRIO_USER, 0)          #=> 19
  Process.getpriority(Process::PRIO_PROCESS, 0)       #=> 19

Process::setrlimit[править]


 Process.setrlimit(resource, cur_limit, max_limit)        => nil
 Process.setrlimit(resource, cur_limit)                   => nil

Sets the resource limit of the process. cur_limit means current (soft) limit and max_limit means maximum (hard) limit. If max_limit is not given, cur_limit is used. resource indicates the kind of resource to limit. The list of resources are OS dependent. Ruby may support following resources.

Process::RLIMIT_CORE
core size (bytes) (SUSv3)
Process::RLIMIT_CPU
CPU time (seconds) (SUSv3)
Process::RLIMIT_DATA
data segment (bytes) (SUSv3)
Process::RLIMIT_FSIZE
file size (bytes) (SUSv3)
Process::RLIMIT_NOFILE
file descriptors (number) (SUSv3)
Process::RLIMIT_STACK
stack size (bytes) (SUSv3)
Process::RLIMIT_AS
total available memory (bytes) (SUSv3, NetBSD, FreeBSD, OpenBSD but 4.4BSD-Lite)
Process::RLIMIT_MEMLOCK
total size for mlock(2) (bytes) (4.4BSD, GNU/Linux)
Process::RLIMIT_NPROC
number of processes for the user (number) (4.4BSD, GNU/Linux)
Process::RLIMIT_RSS
resident memory size (bytes) (4.2BSD, GNU/Linux)
Process::RLIMIT_SBSIZE
all socket buffers (bytes) (NetBSD, FreeBSD)

Other Process::RLIMIT_??? constants may be defined.

cur_limit and max_limit may be Process::RLIM_INFINITY, which means that the resource is not limited. They may be Process::RLIM_SAVED_MAX or Process::RLIM_SAVED_CUR too. See system setrlimit(2) manual for details.

Process::setsid[править]


 Process.setsid   => fixnum

Establishes this process as a new session and process group leader, with no controlling tty. Returns the session id. Not available on all platforms.

  Process.setsid   #=> 27422

Process::times[править]


 Process.times   => aStructTms

Returns a Tms structure (see Struct::Tms on page 388) that contains user and system CPU times for this process.

  t = Process.times
  [ t.utime, t.stime ]   #=> [0.0, 0.02]

Process::uid[править]


 Process.uid           => fixnum
 Process::UID.rid      => fixnum
 Process::Sys.getuid   => fixnum

Returns the (real) user ID of this process.

  Process.uid   #=> 501

Process::uid=[править]


 Process.uid= integer   => numeric

Sets the (integer) user ID for this process. Not available on all platforms.

Process::wait[править]


 Process.wait()                     => fixnum
 Process.wait(pid=-1, flags=0)      => fixnum
 Process.waitpid(pid=-1, flags=0)   => fixnum

Waits for a child process to exit, returns its process id, and sets $? to a Process::Status object containing information on that process. Which child it waits on depends on the value of pid:

Waits for the child whose process ID equals pid. Waits for any child whose process group ID equals that of the calling process. Waits for any child process (the default if no pid is given).

Waits for any child whose process group ID equals the absolute value of pid.

The flags argument may be a logical or of the flag values Process::WNOHANG (do not block if no child available) or Process::WUNTRACED (return stopped children that haven't been reported). Not all flags are available on all platforms, but a flag value of zero will work on all platforms. Calling this method raises a SystemError if there are no child processes. Not available on all platforms.

  include Process
  fork { exit 99 }                 #=> 27429
  wait                             #=> 27429
  $?.exitstatus                    #=> 99
  pid = fork { sleep 3 }           #=> 27440
  Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
  waitpid(pid, Process::WNOHANG)   #=> nil
  Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
  waitpid(pid, 0)                  #=> 27440
  Time.now                         #=> Wed Apr 09 08:57:12 CDT 2003

Process::wait2[править]


 Process.wait2(pid=-1, flags=0)      => [pid, status]
 Process.waitpid2(pid=-1, flags=0)   => [pid, status]

Waits for a child process to exit (see Process::waitpid for exact semantics) and returns an array containing the process id and the exit status (a Process::Status object) of that child. Raises a SystemError if there are no child processes.

  Process.fork { exit 99 }   #=> 27437
  pid, status = Process.wait2
  pid                        #=> 27437
  status.exitstatus          #=> 99

Process::waitall[править]


 Process.waitall   => [ [pid1,status1], ...]

Waits for all children, returning an array of pid/status pairs (where status is a Process::Status object).

  fork { sleep 0.2; exit 2 }   #=> 27432
  fork { sleep 0.1; exit 1 }   #=> 27433
  fork {            exit 0 }   #=> 27434
  p Process.waitall

produces:

  [[27434, #<Process::Status: pid=27434,exited(0)>],
   [27433, #<Process::Status: pid=27433,exited(1)>],
   [27432, #<Process::Status: pid=27432,exited(2)>]]

Process::waitpid[править]


 Process.wait()                     => fixnum
 Process.wait(pid=-1, flags=0)      => fixnum
 Process.waitpid(pid=-1, flags=0)   => fixnum

Waits for a child process to exit, returns its process id, and sets $? to a Process::Status object containing information on that process. Which child it waits on depends on the value of pid:

Waits for the child whose process ID equals pid. Waits for any child whose process group ID equals that of the calling process. Waits for any child process (the default if no pid is given).

Waits for any child whose process group ID equals the absolute value of pid.

The flags argument may be a logical or of the flag values Process::WNOHANG (do not block if no child available) or Process::WUNTRACED (return stopped children that haven't been reported). Not all flags are available on all platforms, but a flag value of zero will work on all platforms. Calling this method raises a SystemError if there are no child processes. Not available on all platforms.

  include Process
  fork { exit 99 }                 #=> 27429
  wait                             #=> 27429
  $?.exitstatus                    #=> 99
  pid = fork { sleep 3 }           #=> 27440
  Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
  waitpid(pid, Process::WNOHANG)   #=> nil
  Time.now                         #=> Wed Apr 09 08:57:09 CDT 2003
  waitpid(pid, 0)                  #=> 27440
  Time.now                         #=> Wed Apr 09 08:57:12 CDT 2003

Process::waitpid2[править]


 Process.wait2(pid=-1, flags=0)      => [pid, status]
 Process.waitpid2(pid=-1, flags=0)   => [pid, status]

Waits for a child process to exit (see Process::waitpid for exact semantics) and returns an array containing the process id and the exit status (a Process::Status object) of that child. Raises a SystemError if there are no child processes.

  Process.fork { exit 99 }   #=> 27437
  pid, status = Process.wait2
  pid                        #=> 27437
  status.exitstatus          #=> 99

Process#create[править]


 create(args)

Process.create(key => value, ...) => ProcessInfo This is a wrapper for the CreateProcess() function. It executes a process, returning a ProcessInfo struct. It accepts a hash as an argument. There are six primary keys:

  • app_name (mandatory)
  • inherit (default: false)
  • process_inherit (default: false)
  • thread_inherit (default: false)
  • creation_flags (default: 0)
  • cwd (default: Dir.pwd)
  • startup_info (default: nil)
  • environment (default: nil)

Of these, the 'app_name' must be specified or an error is raised. The startup_info key takes a hash. Its keys are attributes that are part of the StartupInfo struct, and are generally only meaningful for GUI or console processes. See the documentation on CreateProcess() and the StartupInfo struct on MSDN for more information.

  • desktop
  • title
  • x
  • y
  • x_size
  • y_size
  • x_count_chars
  • y_count_chars
  • fill_attribute
  • sw_flags
  • startf_flags

The relevant constants for 'creation_flags', 'sw_flags' and 'startf_flags' are included in the Windows::Process, Windows::Console and Windows::Window modules. These come with the windows-pr package, a prerequisite of this package. The ProcessInfo struct contains the following members:

  • process_handle - The handle to the newly created process
  • thread_handle - The handle to the primary thread of the newly created
  • process.
  • process_id - Process ID.
  • thread_id - Thread ID.

Process#fork[править]


 fork() {|| ...}

Creates the equivalent of a subshell via the CreateProcess() function. This behaves in a manner that is similar, but not identical to, the Kernel.fork method for Unix.

Process#kill[править]


 kill(signal, *pids)

Sends the given signal to an array of process id's. The signal may be any value from 0 to 9, or the special strings 'SIGINT' (or 'INT'), 'SIGBRK' (or 'BRK') and 'SIGKILL' (or 'KILL'). An array of successfully killed pids is returned. Signal 0 merely tests if the process is running without killing it. Signal 2 sends a CTRL_C_EVENT to the process. Signal 3 sends a CTRL_BRK_EVENT to the process. Signal 9 kills the process in a harsh manner. Signals 1 and 4-8 kill the process in a nice manner. SIGINT/INT corresponds to signal 2 SIGBRK/BRK corresponds to signal 3 SIGKILL/KILL corresponds to signal 9 Signals 2 and 3 only affect console processes, and then only if the process was created with the CREATE_NEW_PROCESS_GROUP flag.

Process#wait[править]


 wait()

Waits for any child process to exit and returns the process id of that child. Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release.

Process#wait2[править]


 wait2()

Waits for any child process to exit and returns an array containing the process id and the exit status of that child. Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release.

Process#waitpid[править]


 waitpid(pid)

Waits for the given child process to exit and returns that pid. Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release.

Process#waitpid2[править]


 waitpid2(pid)

Waits for the given child process to exit and returns an array containing the process id and the exit status. Note that the $? (Process::Status) global variable is NOT set. This may be addressed in a future release.

Класс Range[править]

Объекты класса Range представляют собой интервал - множество значений между началом и концом интервала. Интервалы могу быть созданы с использованием литералов s..e и s...e, или при помощи метода Range::new. Интервалы, созданные при помощи .., идут с начала по конец включительно. Напротив, интервалы, которые созданы при помощи ... исключают последнее значение. Когда интервалы используются в итераторах, они возвращают каждое значение из заданного диапазона.

(-1..-5).to_a      #-> []
(-5..-1).to_a      #-> [-5, -4, -3, -2, -1]
('a'..'e').to_a    #-> ["a", "b", "c", "d", "e"]
('a'...'e').to_a   #-> ["a", "b", "c", "d"]

Интервалы могут быть созданы с использованием объектов любого типа, при условии, что они сравнимы при помощи оператора <=> и содержат метод succ, который возвращает следующий объект последовательности.

class Xs                # represent a string of 'x's
  include Comparable
  attr :length
  def initialize(n)
    @length = n
  end
  def succ
    Xs.new(@length + 1)
  end
  def <=>(other)
    @length <=> other.length
  end
  def to_s
    sprintf "%2d #{inspect}", @length
  end
  def inspect
    'x' * @length
  end
end

r = Xs.new(3)..Xs.new(6)   #-> xxx..xxxxxx
r.to_a                     #-> [xxx, xxxx, xxxxx, xxxxxx]
r.member?(Xs.new(5))       #-> true

В предыдущем примере, класс Xs подключает примесь Comparable. Поэтому метод Enumerable#member? имеет возможность использовать оператор == для проверки эквивалентности. Подключенная примесь Comparable реализует оператор ==, но для его корректной работы в классе Xs должен быть реализован оператор <=>.


Примеси

Enumerable (all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find, find_all, grep, group_by, include?, index_by, inject, map, max, member?, min, partition, reject, select, sort, sort_by, sum, to_a, to_set, zip)

Методы класса

new

Методы объекта

===, ==, begin, each, end, eql?, exclude_end?, first, hash, include?, inspect, last, member?, step, to_s

Range::new[править]


Range.new(start, end, exclusive=false)    #-> range

Создает интервал, используя start и end. Если третий параметр пропущен или равен false, то range будет включать конечный объект (равный end); иначе он будет исключен.

Range#==[править]


rng == obj    #-> true or false

Возвращает true только если obj является интервалом, начальный и конечный объект которого эквивалентны соответствующим параметрам rng (сравнивается при помощи ==), и результат метода #exclude_end? такой же, как и у rng.

(0..2) == (0..2)            #-> true
(0..2) == Range.new(0,2)    #-> true
(0..2) == (0...2)           #-> false

Range#===[править]


rng === obj       #->  true или false
rng.member?(val)  #->  true или false
rng.include?(val) #->  true или false

Возвращает true если obj является элементом rng, false иначе. Оператор сравнения === используется для сопоставления в конструкции case.

case 79
   when 1..50   then   print "низко\n"
   when 51..75  then   print "средне\n"
   when 76..100 then   print "высоко\n"
end

результат:

высоко

(еще известен как member?, include?)

Range#begin[править]


rng.first    #-> obj
rng.begin    #-> obj

Возвращает первый объект из интервала rng.

(еще известен как first)

Range#each[править]


rng.each {| i | block } #-> rng

Перебирает элементы rng, которые передаются каждую итерацию внутрь блока. Вы можете осуществить перебор только в том случае, если начальный объект поддерживает метод succ (таким образом перебор элементов из интервала, состоящего из объектов Float невозможен).

(10..15).each do |n|
   print n, ' '
end

результат:

10 11 12 13 14 15

Range#end[править]


rng.end    #-> obj
rng.last   #-> obj

Возвращает элемент, который в rng объявлен как последний.

(1..10).end    #-> 10
(1...10).end   #-> 10

(еще известен как last)

Range#eql?[править]


rng.eql?(obj)    #-> true или false

Возвращает true только если obj является интервалом, начальный и конечный объект которого эквивалентны соответствующим параметрам rng (сравнивается при помощи #eql?), и результат метода #exclude_end? такой же, как и у rng.

(0..2) == (0..2)            #-> true
(0..2) == Range.new(0,2)    #-> true
(0..2) == (0...2)           #-> false

Range#exclude_end?[править]


rng.exclude_end?    #-> true или false

Возвращает true если rng не включает последний элемент (создан при помощи ...).

Range#first[править]


rng.first    #-> obj
rng.begin    #-> obj

Возвращает первый объект из интервала rng.

(еще известен как begin)

Range#hash[править]


rng.hash    #-> fixnum

Возвращает контрольную сумму, которая для двух диапазонов с одинаковыми начальными и конечными объектами, а также с одинаковыми значениями метода #exclude_end? --- будет совпадать.

Range#include?[править]


rng === obj       #->  true или false
rng.member?(val)  #->  true или false
rng.include?(val) #->  true или false

Возвращает true если obj является элементом rng, false иначе. Оператор сравнения === используется для сопоставления в конструкции case.

case 79
   when 1..50   then   print "низко\n"
   when 51..75  then   print "средне\n"
   when 76..100 then   print "высоко\n"
end

результат:

высоко

(еще известен как ===, member?)

Range#inspect[править]


rng.inspect  #-> string

Преобразует инретвал rng в печатную форму (использует метод inspect для преобразования начального и конечного объектов).

Range#last[править]


rng.end    #-> obj
rng.last   #-> obj

Возвращает элемент, который в rng объявлен как последний.

(1..10).end    #-> 10
(1...10).end   #-> 10

(еще известен как end)

Range#member?[править]


rng === obj       #->  true или false
rng.member?(val)  #->  true или false
rng.include?(val) #->  true или false

Возвращает true если obj является элементом rng, false иначе. Оператор сравнения === используется для сопоставления в конструкции case.

case 79
   when 1..50   then   print "низко\n"
   when 51..75  then   print "средне\n"
   when 76..100 then   print "высоко\n"
end

результат:

высоко

(еще известен как ===, include?)

Range#step[править]


rng.step(n=1) {| obj | block }    #-> rng

Перебирает элементы из диапазона rng, передавая каждый n-ый элемент в блок. Если диапазон состоит из целых чисел или строк, то элементы вычисляются целочисленным делением. Иначе step использует метод succ для перебора элментов. Следующий код использует класс Xs, который использовался нами ранее (см. Range).

range = Xs.new(1)..Xs.new(10)
range.step(2) {|x| puts x}
range.step(3) {|x| puts x}

результат:

1 x
3 xxx
5 xxxxx
7 xxxxxxx
9 xxxxxxxxx
1 x
4 xxxx
7 xxxxxxx
10 xxxxxxxxxx

Range#to_s[править]


rng.to_s   #-> string

Преобразует интервал rng в печатную форму.

Класс Regexp[править]

Документ-класс: Regexp Regexp содержит регулярные выражения, используется для сопоставления шаблона с строками. Регулярные выражения создаются с помощью /.../ и %r{...} знаков, а также с конструктором Regexp::new.


Константы

EXTENDED, IGNORECASE, MULTILINE

Методы класса

compile, escape, last_match, new, quote, union, yaml_new

Методы объекта

&, ===, ==, =~, casefold?, eql?, hash, inspect, kcode, match, options, source, to_s, to_yaml, ||, ~

Regexp::compile[править]


 Regexp::compile(...)

Синоним для Regexp.new

Regexp::escape[править]


 Regexp.escape(str)   => a_str
 Regexp.quote(str)    => a_str

Вытесняет любые символы, которые имеют особое значение в регулярном выражении. Возвращает новую экранированную строку или self, если никакие символы не экранированы. Для любой строки, Regexp.escape(str)=~str будет true.

  Regexp.escape('\*?{}.')   #=> \\*\?\{\}\.

Regexp::last_match[править]


 Regexp.last_match           => matchdata
 Regexp.last_match(fixnum)   => str

The first form returns the MatchData object generated by the last successful pattern match. Equivalent to reading the global variable $~. The second form returns the nth field in this MatchData object.

  /c(.)t/ =~ 'cat'       #=> 0
  Regexp.last_match      #=> #<MatchData:0x401b3d30>
  Regexp.last_match(0)   #=> "cat"
  Regexp.last_match(1)   #=> "a"
  Regexp.last_match(2)   #=> nil

Regexp::new[править]


 Regexp.new(string [, options [, lang]])       => regexp
 Regexp.new(regexp)                            => regexp
 Regexp.compile(string [, options [, lang]])   => regexp
 Regexp.compile(regexp)                        => regexp

Constructs a new regular expression from pattern, which can be either a String or a Regexp (in which case that regexp's options are propagated, and new options may not be specified (a change as of Ruby 1.8). If options is a Fixnum, it should be one or more of the constants Regexp::EXTENDED, Regexp::IGNORECASE, and Regexp::MULTILINE, or-ed together. Otherwise, if options is not nil, the regexp will be case insensitive. The lang parameter enables multibyte support for the regexp: `n', `N' = none, `e', `E' = EUC, `s', `S' = SJIS, `u', `U' = UTF-8.

  r1 = Regexp.new('^a-z+:\s+\w+')           #=> /^a-z+:\s+\w+/
  r2 = Regexp.new('cat', true)               #=> /cat/i
  r3 = Regexp.new('dog', Regexp::EXTENDED)   #=> /dog/x
  r4 = Regexp.new(r2)                        #=> /cat/i

Regexp::quote[править]


 Regexp.escape(str)   => a_str
 Regexp.quote(str)    => a_str

Escapes any characters that would have special meaning in a regular expression. Returns a new escaped string, or self if no characters are escaped. For any string, Regexp.escape(str)=~str will be true.

  Regexp.escape('\*?{}.')   #=> \\*\?\{\}\.

Regexp::union[править]


 Regexp.union([pattern]*)   => new_str

Return a Regexp object that is the union of the given patterns, i.e., will match any of its parts. The patterns can be Regexp objects, in which case their options will be preserved, or Strings. If no arguments are given, returns /(?!)/.

  Regexp.union                         #=> /(?!)/
  Regexp.union("penzance")             #=> /penzance/
  Regexp.union("skiing", "sledding")   #=> /skiing|sledding/
  Regexp.union(/dogs/, /cats/i)        #=> /(?-mix:dogs)|(?i-mx:cats)/

Regexp::yaml_new[править]


 Regexp::yaml_new( klass, tag, val )

(нет описания...)

Regexp#&[править]


 &(other)

(нет описания...)

Regexp#==[править]


 rxp == other_rxp      => true or false
 rxp.eql?(other_rxp)   => true or false

Equality---Two regexps are equal if their patterns are identical, they have the same character set code, and their casefold? values are the same.

  /abc/  == /abc/x   #=> false
  /abc/  == /abc/i   #=> false
  /abc/u == /abc/n   #=> false

Regexp#===[править]


 rxp === str   => true or false

Case Equality---Synonym for Regexp#=~ used in case statements.

  a = "HELLO"
  case a
  when /^[a-z]*$/; print "Lower case\n"
  when /^[A-Z]*$/; print "Upper case\n"
  else;            print "Mixed case\n"
  end

produces:

  Upper case

Regexp#=~[править]


 rxp.match(str)   => matchdata or nil

Returns a MatchData object describing the match, or nil if there was no match. This is equivalent to retrieving the value of the special variable $~ following a normal match.

  /(.)(.)(.)/.match("abc")[2]   #=> "b"

Regexp#casefold?[править]


 rxp.casefold?   => true or false

Returns the value of the case-insensitive flag.

Regexp#eql?[править]


 rxp == other_rxp      => true or false
 rxp.eql?(other_rxp)   => true or false

Equality---Two regexps are equal if their patterns are identical, they have the same character set code, and their casefold? values are the same.

  /abc/  == /abc/x   #=> false
  /abc/  == /abc/i   #=> false
  /abc/u == /abc/n   #=> false

Regexp#hash[править]


 rxp.hash   => fixnum

Produce a hash based on the text and options of this regular expression.

Regexp#inspect[править]


 rxp.inspect   => string

Produce a nicely formatted string-version of rxp. Perhaps surprisingly, #inspect actually produces the more natural version of the string than #to_s.

   /ab+c/ix.to_s         #=> /ab+c/ix

Regexp#kcode[править]


 rxp.kcode   => str

Returns the character set code for the regexp.

Regexp#match[править]


 rxp.match(str)   => matchdata or nil

Returns a MatchData object describing the match, or nil if there was no match. This is equivalent to retrieving the value of the special variable $~ following a normal match.

  /(.)(.)(.)/.match("abc")[2]   #=> "b"

Regexp#options[править]


 rxp.options   => fixnum

Returns the set of bits corresponding to the options used when creating this Regexp (see Regexp::new for details. Note that additional bits may be set in the returned options: these are used internally by the regular expression code. These extra bits are ignored if the options are passed to Regexp::new.

  Regexp::IGNORECASE                  #=> 1
  Regexp::EXTENDED                    #=> 2
  Regexp::MULTILINE                   #=> 4
  /cat/.options                       #=> 128
  /cat/ix.options                     #=> 131
  Regexp.new('cat', true).options     #=> 129
  Regexp.new('cat', 0, 's').options   #=> 384
  r = /cat/ix
  Regexp.new(r.source, r.options)     #=> /cat/ix

Regexp#source[править]


 rxp.source   => str

Returns the original string of the pattern.

  /ab+c/ix.source   #=> "ab+c"

Regexp#to_s[править]


 rxp.to_s   => str

Returns a string containing the regular expression and its options (using the (?xxx:yyy) notation. This string can be fed back in to Regexp::new to a regular expression with the same semantics as the original. (However, Regexp#== may not return true when comparing the two, as the source of the regular expression itself may differ, as the example shows). Regexp#inspect produces a generally more readable version of rxp.

  r1 = /ab+c/ix         #=> /ab+c/ix
  s1 = r1.to_s          #=> "(?ix-m:ab+c)"
  r2 = Regexp.new(s1)   #=> /(?ix-m:ab+c)/
  r1 == r2              #=> false
  r1.source             #=> "ab+c"
  r2.source             #=> "(?ix-m:ab+c)"

Regexp#to_yaml[править]


 to_yaml( opts = {} )

(нет описания...)

Regexp#|[править]


 |(other)

(нет описания...)

Regexp#~[править]


 ~ rxp   => integer or nil

Match---Matches rxp against the contents of $_. Equivalent to rxp =~ $_.

  $_ = "input data"
  ~ /at/   #=> 7

Класс String[править]

Строки хранят и манипулируют произвольными последовательностями байт (обычно это символы). Строки могут быть созданы при помощи метода String::new или как литералы. Для избежания трудноуловимых ошибок в коде, необходимо знать методы, которые меняют исходную строку (а не создают новую). Обычно имена этих методов заканчиваются на !. Если имя метода не заканчивается на !, то данный метод создает новую строку, а не модифицирует исходную. Правда, как и у любого правила, есть исключения. Например, метод String#[]=.


Примеси

Comparable (<, <=, ==, >, >=, between?),

Enumerable (all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find, find_all, grep, group_by, include?, index_by, inject, map, max, member?, min, partition, reject, select, sort, sort_by, sum, to_a, to_set, zip)

Константы

DeletePatternCache, HashCache, PATTERN_EUC, PATTERN_SJIS, PATTERN_UTF8, RE_EUC, RE_SJIS, RE_UTF8, SUCC, SqueezePatternCache, TrPatternCache

Методы класса

new

Методы объекта

[]=, [], %, *, +, <<, <=>, ==, =~, ascii_only?, capitalize!, capitalize, casecmp, center, chars, chomp!, chomp, chop!, chop, clear, concat, count, crypt, delete!, delete, delete_prefix, delete_prefix!, downcase!, downcase, dump, each_byte, each_char, each_line, each, empty?, eql?, gsub!, gsub, hash, hex, include?, index, insert, inspect, intern, length, ljust, lstrip!, lstrip, match, next!, next, nstrip, oct, ord, replace, reverse!, reverse, rindex, rjust, rstrip!, rstrip, scanf, scan, size, slice!, slice, split, squeeze!, squeeze, strip!, strip, sub!, sub, succ!, succ, sum, swapcase!, swapcase, to_blob, to_a, to_c, to_f, to_i, to_str, to_sym, to_s, tr!, tr_s!, tr_s, tr, unpack, upcase!, upcase, upto

String::new[править]


String.new(str="")   #-> new_str

Возвращает новую строку, которая содержит копию строки str, передаваемой в качестве параметра.

String#%[править]


str % arg   #-> new_str

Форматирование строки. В управляющую строку str вместо спецификаторов преобразования подставляются данные из arg. Если в строке str указано несколько спецификаторов преобразования, то arg должен быть массивом.

"%05d" % 123                       #-> "00123"
"%-5s: %08x" % [ "ID", self.id ]   #-> "ID   : 200e14d6"
Информация

Описание формата управляющей строки и спецификаторов можно посмотреть в описании метода Kernel::sprintf

String#*[править]


str * integer  #-> new_str

Повторение — возвращает новую строку, которая состоит из integer-копий строки str.

"Ho! " * 3   #-> "Ho! Ho! Ho! "

String#+[править]


str + other_str   #-> new_str

Сцепление — возвращает новую строку, состоящую из строк str и other_str.

"Hello from " + self.to_s   #-> "Hello from main"
Информация

Полезно посмотреть на методы << и concat, которые имеют схожую функциональность

String#<<[править]


str << fixnum        #-> str
str.concat(fixnum)   #-> str
str << obj           #-> str
str.concat(obj)      #-> str

Добавление — присоединяет аргумент к str. Если аргумент типа Fixnum в диапазоне от 0 до 255, то он перед присоединением конвертируется в символ.

a = "hello ";
a << "world"   #-> "hello world"
a << 33        #-> "hello world!"
Информация

Методы << и concat — абсолютно идентичны, то есть являются именами одного и того же метода

String#<=>[править]


str <=> other_str   #-> -1, 0, +1

Сравнение — возвращает -1, если other_str меньше str; возвращает 0, если other_str и str равны; возвращает +1, если other_str больше str. Если строки различаются по длине, но эквивалентны на длине самой короткой из двух, то большей считается та, которая длиннее. Если переменная $= равна false, то сравнение базируется на сравнении двоичных значений каждого символа в строке. В старых версиях Руби, изменением $= можно было добиться регистронезависимого сравнения, но теперь эту функцию выполняет метод casecmp, который и рекомендуется использовать для этих целей.

"abcdef" <=> "abcde"     #-> 1
"abcdef" <=> "abcdef"    #-> 0
"abcdef" <=> "abcdefg"   #-> -1
"abcdef" <=> "ABCDEF"    #-> 1
Информация

Полезно посмотреть на метод casecmp, который имеет схожую функциональность

Информация

Метод <=> служит основой для таких методов, как: <, <=, >, >= и between?, которые подключаются вместе с модулем Comparable

String#==[править]


str == obj   #-> true или false

Эквивалентность — если строки str и obj не совпадают, то возвращается false. Возвращается true только в случае, когда код str <=> obj возвращает 0.

String#=~[править]


str =~ obj   #-> fixnum или nil

Сопоставление с шаблоном — если obj является правилом, то он используется как шаблон для сопоставления с str и возвращает позицию с которой найдено соспоставление или nil, если такого сопоставления найти не удалось. Иначе, происходит вызов метода obj.=~, которому передается str как аргумент. По умолчанию, метод =~ в классе Object возвращает false.

"cat o' 9 tails" =~ /\d/   #-> 7
"cat o' 9 tails" =~ 9      #-> false
Информация

Полезно посмотреть на метод match, который имеет схожую функциональность

String#[][править]


str[index]                  #-> символ или nil
str[start, length]          #-> new_str или nil
str[range]                  #-> new_str или nil
str[regexp]                 #-> new_str или nil
str[regexp, index]          #-> new_str или nil
str[other_str]              #-> new_str или nil
str.slice(index)            #-> fixnum или nil
str.slice(start, length)    #-> new_str или nil
str.slice(range)            #-> new_str или nil
str.slice(regexp)           #-> new_str или nil
str.slice(regexp, index)    #-> new_str или nil
str.slice(other_str)        #-> new_str или nil

Получение подстроки или символа — возвращает код символа с индексом index, или подстроку длины length, начиная с индекса start, или подстроку, которая располагается в диапазоне range. Во всех этих вариантах вызова отрицательная индексация подразумевает отсчет с конца строки str. Возвращается nil, если индекс index выходит за пределы допустимого диапазона, размер length запрашиваемой подстроки отрицательный или начало диапазона range попадает после конца строки str. Если передается правило regexp, то возвращается фрагмент строки str, который удовлетворяет правилу regexp (или nil, если такого совпадения найти не удалось). Если задан дополнительный параметр index, то возвращается содержимое группировки правила с номером index (если index равен 0, то возвращается фрагмент строки, который удовлетворяет правилу regexp). Если в качестве аргумента передается строка other_str, то возвращается строка other_str, если она является подстрокой строки str (или nil, иначе).

a = "hello there"
a[1]                   #-> "e"
a[1,3]                 #-> "ell"
a[1..3]                #-> "ell"
a[-3,2]                #-> "er"
a[-4..-2]              #-> "her"
a[12..-1]              #-> nil
a[-2..-4]              #-> ""
a[/[aeiou](.)\1/]      #-> "ell"
a[/[aeiou](.)\1/, 0]   #-> "ell"
a[/[aeiou](.)\1/, 1]   #-> "l"
a[/[aeiou](.)\1/, 2]   #-> nil
a["lo"]                #-> "lo"
a["bye"]               #-> nil
Информация

Методы slice и [] («батарейка») — абсолютно идентичны!

String#[]=[править]


str[index] = fixnum
str[index] = new_str
str[start, length] = new_str
str[range] = new_str
str[regexp] = new_str
str[regexp, index] = new_str
str[other_str] = new_str

Присваивание значения элементу — заменяет часть или все содержимое строки str. Внутри квадратных скобок используются те же самые параметры, что и в [] («батарейка»). Если заменяемая строка не совпадает по размеру с заменяющей, то происходит соответствующая адаптация. Если правило или строка или индекс не позволяют определить позицию для замены, то возникает ошибка IndexError. Если используется форма вызова с regexp и index, то происходит замена подстроки, которая совпадает группировкой в regexp с номером index. Формы вызова, которым передается index или start могут вызвать ошибку IndexError, если их значение выходит за пределы индексации строки; форма вызова с range может вызвать ошибку RangeError, а форма вызова с regexp или other_str тихо реагируют на возможные ошибки (отсутствие совпадение с правилом или строкой).

String#ascii_only?[править]


str.ascii_only?   #-> true или false

Возвращает true для строки, которая содержит только ASCII символы. В противном случае возвращает false.

"abc".force_encoding("UTF-8").ascii_only?          #=> true
"abc\u{6666}".force_encoding("UTF-8").ascii_only?          #=> false

String#bytesize[править]


bytesize   #-> integer

Возвращает количество байтов в себе:

"\x80\u3042".bytesize     #=> 4
"hello".bytesize          #=> 5
Информация

Полезно посмотреть на методы length и size, которые имеют схожую функциональность

String#byteslice[править]


byteslice(integer)   #-> new_str или nil
byteslice(integer, integer) #-> new_str или nil
byteslice(range) #-> new_str или nil

Байтовая ссылка - если передано одно целое число, возвращает подстроку из одного байта в этой позиции. Если переданы два объекта Integer, возвращает подстроку, начиная со смещения, заданного первым, и длину, заданную вторым. Если задан диапазон, возвращается подстрока, содержащая байты со смещениями, заданными диапазоном. Во всех трех случаях, если смещение отрицательное, оно отсчитывается от конца str. Возвращает nil, если начальное смещение выходит за пределы строки, длина отрицательна или начало диапазона больше конца. Кодировка полученной строки сохраняет исходную кодировку.

"hello".byteslice(1)     #=> "e"
"hello".byteslice(-1)    #=> "o"
"hello".byteslice(1, 2)  #=> "el"
"\x80\u3042".byteslice(1, 3) #=> "\u3042"
"\x03\u3042\xff".byteslice(1..3) #=> "\u3042"

String#capitalize[править]


str.capitalize   #-> new_str

Возвращает копию строки str в которой первый символ преобразуется в верхний регистр, а остальные — в нижний.

"hello".capitalize    #-> "Hello"
"HELLO".capitalize    #-> "Hello"
"123ABC".capitalize   #-> "123abc"
Информация

Полезно посмотреть на методы upcase, downcase и swapcase, которые имеют схожую функциональность

String#capitalize![править]


str.capitalize!   #-> str или nil

Модифицирует строку str по правилу: первый символ преобразуется в верхний регистр, а остальные — в нижний. Возвращает nil, если изменения не требуются.

a = "hello"
a.capitalize!   #-> "Hello"
a               #-> "Hello"
a.capitalize!   #-> nil
Информация

Полезно посмотреть на методы upcase!, downcase! и swapcase!, которые имеют схожую функциональность

String#casecmp[править]


str.casecmp(other_str)   #-> -1, 0, +1

Регистронезависимая версия метода <=>.

"abcdef".casecmp("abcde")     #-> 1
"aBcDeF".casecmp("abcdef")    #-> 0
"abcdef".casecmp("abcdefg")   #-> -1
"abcdef".casecmp("ABCDEF")    #-> 0

String#center[править]


str.center(integer, padstr)   #-> new_str

Если integer больше, чем str.length, то возвращает новую строку, длина которой равна integer, строка str располагается посередине, обитая символами строки padstr; иначе, возвращает str.

"hello".center(4)         #-> "hello"
"hello".center(20)        #-> "       hello        "
"hello".center(20, '123') #-> "1231231hello12312312"
Информация

Полезно посмотреть на методы ljust и rjust, которые имеют схожую функциональность

String#chars[править]


str.chars   #-> array

Возвращает массив, содержащий символы строки, из которой вызывается метод.

"hello".chars            #-> ["h", "e", "l", "l", "o"]

String#chomp[править]


str.chomp(separator=$/)   #-> new_str

Возвращает новую строку, которая является копией строки str в которой удален последний символ separator. Если системная переменная $/ не была изменена и не передается параметр separator, то метод chomp удалит завершающие символы строки (такие как \n, \r и \r\n).

"hello".chomp            #-> "hello"
"hello\n".chomp          #-> "hello"
"hello\r\n".chomp        #-> "hello"
"hello\n\r".chomp        #-> "hello\n"
"hello\r".chomp          #-> "hello"
"hello \n there".chomp   #-> "hello \n there"
"hello".chomp("llo")     #-> "he"
Информация

Полезно посмотреть на метод chop, который имеет схожую функциональность

String#chomp![править]


str.chomp!(separator=$/)   #-> str или nil

Модифицирует строку str по алгоритму, описанному в методе chomp. Возвращает обработанную строку str или nil, если изменения не требуются.

"hello".chomp!            #-> nil
"hello\n".chomp!          #-> "hello"
"hello".chomp!("llo")     #-> "he"
Информация

Полезно посмотреть на метод chop!, который имеет схожую функциональность

String#chop[править]


str.chop   #-> new_str

Возвращает копию строки str из которой удален последний символ. Если строка заканчивается комбинацией символов \r\n, то будет удалена вся комбинация. Вызов метода chop от пустой строки возвращает пустую строку.

"string\r\n".chop   #-> "string"
"string\n\r".chop   #-> "string\n"
"".chop             #-> ""
"string".chop       #-> "strin"
"x".chop.chop       #-> ""
Информация

В качестве альтернативы методу chop лучше использовать метод chomp, который удаляет только символы перевода строки, а не просто последний символ. Это позволит избежать многих трудновыявляемых ошибок в будущем

String#chop![править]


str.chop!   #-> new_str или nil

Модифицирует строку str по алгоритму, описанному в методе chop. Возвращает обработанную строку str или nil, если изменения не требуются (например, если метод chop! был вызван от пустой строки).

"string\r\n".chop!   #-> "string"
"string\n\r".chop!   #-> "string\n"
"".chop!             #-> nil
"string".chop!       #-> "strin"
"x".chop.chop!       #-> ""
Информация

В качестве альтернативы методу chop! лучше использовать метод chomp!, который удаляет только символы перевода строки, а не просто последний символ. Это позволит избежать многих трудновыявляемых ошибок в будущем

String#chr[править]


str.chr   #-> string

Возвращает односимвольную строку с начала строки.

str = "abcde"
str.chr           #-> "a"
str = "bcde"
str.chr           #-> "b"

String#clear[править]


str.clear   #-> empty string

Делает строку, из которой вызывается, пустой.

str = "abcde"
str.clear           #-> ""

String#concat[править]


str << fixnum        #-> str
str.concat(fixnum)   #-> str
str << obj           #-> str
str.concat(obj)      #-> str

Добавление — присоединяет аргумент к str. Если аргумент типа Fixnum в диапазоне от 0 до 255, то он перед присоединением конвертируется в символ.

a = "hello ";
a.concat("world")   #-> "hello world"
a.concat(33)        #-> "hello world!"
Информация

Методы << и concat — абсолютно идентичны, то есть являются именами одного и того же метода

String#count[править]


str.count(other_str*)   #-> fixnum

Каждый параметр other_str преобразуется в множество символов. Метод подсчитывает количество символов str, которые принадлежат этому множеству. При помощи символа "галочка" (^) задаются исключения из множества. Выражения типа c1-c2 задают множество символов, которые располагаются между символами c1 и c2.

a = "hello world"
a.count "lo"            #-> 5
a.count "lo", "o"       #-> 2
a.count "hello", "^l"   #-> 4
a.count "ej-m"          #-> 4

String#crypt[править]


str.crypt(salt_str)   #-> new_str

Применяет однопроходное криптографическое хеширование к строке str посредством функции crypt из стандартной библиотеки языка Си. Аргументом метода является строка salt_str, которая содержит "шумовые" символы. Она должна быть длиннее двух символов, каждый из которых должен принадлежать множеству [a-zA-Z0-9./].

String#delete[править]


str.delete(other_str*)   #-> new_str

Возвращает копию строки str, в которой удалены все символы, передаваемые параметром.

"hello".delete "l","lo"        #-> "heo"
"hello".delete "lo"            #-> "he"
"hello".delete "aeiou", "^e"   #-> "hell"
"hello".delete "ej-m"          #-> "ho"
Информация

Использует те же самые правила создания множеств символов, что и в методе count

String#delete![править]


str.delete!(other_str*)   #-> str или nil

Удаляет из строки str все символы, передаваемые параметром. Возвращает модифицированную строку str или nil, если строка str не была модифицирована.

str="hello"
str.delete! "l","lo"        #-> "heo"
str                         #-> "heo"
str.delete! "l","lo"        #-> nil
Информация

Использует те же самые правила создания множеств символов, что и в методе count

String#delete_prefix[править]


str.delete_prefix(prefix)   #-> new_str

Возвращает копию str с удаленным начальным префиксом.

str="hello"
str.delete_prefix("hel")        #-> "lo"
str                         #-> "hello"
str.delete_prefix("llo")        #-> "hello"
str                         #-> "hello"

String#delete_prefix![править]


str.delete_prefix!(prefix)   #-> self или nil

Удаляет начальный префикс из строки, возвращая nil, если не было сделано никаких изменений.

str="hello"
str.delete_prefix!("hel")        #-> "lo"
str                         #-> "lo"
str.delete_prefix!("llo")        #-> nil
str                         #-> "hello"
Информация

Полезно посмотреть на метод delete_prefix, который имеет схожую функциональность

String#delete_suffix[править]


str.delete_suffix(suffix)   #-> new_str

Возвращает копию str с удаленным конечным суффиксом.

"hello".delete_suffix("llo") #=> "he"
"hello".delete_suffix("hel") #=> "hello"

String#delete_suffix![править]


str.delete_suffix!(suffix)   #-> self или nil

Удаляет завершающий суффикс из строки, возвращая nil, если не было сделано никаких изменений.

"hello".delete_suffix!("llo") #=> "he"
"hello".delete_suffix!("hel") #=> nil
Информация

Полезно посмотреть на метод delete_suffix, который имеет схожую функциональность

String#downcase[править]


str.downcase   #-> new_str

Возвращает копию строки str в которой все символы вернего регистра заменены на соответствующие символы нижнего.

"hEllO".downcase   #-> "hello"
Информация

Полезно посмотреть на методы capitalize, upcase и swapcase, которые имеют схожую функциональность

String#downcase![править]


str.downcase!   #-> str или nil

Модифицирует строку str по правилу: все символы верхнего регистра преобразовываются в соответствующие символы нижнего. Возвращает nil, если изменения не требуются.

str="hEllO"
str.downcase! #-> "hello"
str           #-> "hello"
str.downcase! #-> nil
Информация

Полезно посмотреть методы capitalize!, upcase! и swapcase!, которые также производят преобразования регистра

String#dump[править]


str.dump   #-> new_str

Создает версию строки str в которой все непечатные символы заменены на \nnn нотацию и все специальные символы экранированы.

"Hello world!\n".dump   #-> "\"Hello world!\\n\""

String#each[править]


str.each(separator=$/) {|substr| block }        #-> str
str.each_line(separator=$/) {|substr| block }   #-> str

Разбивает строку str используя значение параметра separator (по умолчанию separator=$/), передавая каждую из полученных подстрок в качестве параметра блока. Если в качестве параметра separator передается пустая строка, то строка будет делится по символу \n, исключая случай, когда несколько символов \n идут подряд (все символы \n будут засчитываться как один).

print "Example one\n"
"hello\nworld".each {|s| p s}
print "Example two\n"
"hello\nworld".each('l') {|s| p s}
print "Example three\n"
"hello\n\n\nworld".each('') {|s| p s}

результат:

 Example one
 "hello\n"
 "world"
 Example two
 "hel"
 "l"
 "o\nworl"
 "d"
 Example three
 "hello\n\n\n"
 "world"
Информация
  • Обратите внимание, что разделитель separator не удаляется (в отличие от результата работы метода split), а присутствует в результате
  • В качестве результата итератор возвращает исходную строку str
  • Итераторы each и each_line — абсолютно идентичны!

String#each_byte[править]


str.each_byte {|fixnum| block }    #-> str

Передает каждый байт строки str в блок.

"hello".each_byte {|c| print c, ' ' }

результат:

 104 101 108 108 111
Информация

В качестве результата итератор возвращает исходную строку str

String#each_char[править]


str.each_char {|char| block }    #-> str

Передает каждый символ строки str в блок.

"hello".each_char  {|c| print c, ' ' }

результат:

 h e l l o
Информация

В качестве результата итератор возвращает исходную строку str

String#each_line[править]


str.each(separator=$/) {|substr| block }        #-> str
str.each_line(separator=$/) {|substr| block }   #-> str

Разбивает строку str используя значение параметра separator (по умолчанию separator=$/), передавая каждую из полученных подстрок в качестве параметра блока. Если в качестве параметра separator передается пустая строка, то строка будет делится по символу \n, исключая случай, когда несколько символов \n идут подряд (все символы \n будут засчитываться как один).

print "Example one\n"
"hello\nworld".each_line{|s| p s}
print "Example two\n"
"hello\nworld".each_line('l'){|s| p s}
print "Example three\n"
"hello\n\n\nworld".each_line(''){|s| p s}

результат:

 Example one
 "hello\n"
 "world"
 Example two
 "hel"
 "l"
 "o\nworl"
 "d"
 Example three
 "hello\n\n\n"
 "world"
Информация
  • Обратите внимание, что разделитель separator не удаляется (в отличие от результата работы метода split), а присутствует в результате
  • В качестве результата итератор возвращает исходную строку str
  • Итераторы each и each_line — абсолютно идентичны!

String#empty?[править]


str.empty?   #-> true или false

Возвращает true если строка str имеет нулевую длину (то есть, если строка str — пустая).

"hello".empty?   #-> false
"".empty?        #-> true

String#end_with?[править]


str.end_with?([suffixes]+) #-> true или false

Возвращает true, если строка заканчивается одним из указанных суффиксов.

"hello".end_with?("ello")  #-> true

Возвращает true, если один из суффиксов совпадает.

"hello".end_with?("heaven", "ello")     #=> true
"hello".end_with?("heaven", "paradise") #=> false

String#eql?[править]


str.eql?(other_str)   #-> true или false

Две строки называются эквивалентными, если они имеют одинаковое содержимое и длину.

String#gsub[править]


str.gsub(pattern, replacement)       #-> new_str
str.gsub(pattern) {|match| block }   #-> new_str

Возвращает копию строки str, где все совпадения с шаблоном (или строкой) pattern заменены на строку replacement или результат выполнения блока (которому параметром передается результат совпадения).

В результате работы метода, найденное совпадение с шаблоном pattern записывается в специальную переменную $& (наследие языка Perl). В строке replacement возможно использование последовательностей вида \1, \2 и так далее до \9, которые являются ссылками на совпадения с группировками (номер группировки считается слева направо). Внутри блока на группировки можно ссылаться при помощи специальных переменных вида $1, $2 и так далее до $9. Также, выражению в блоке доступны специальные переменные $`, $& и $', которые позволяют получить доступ к подстроке до совпадения, совпадению и подстроке после совпадения, соответственно.

"hello".gsub(/[aeiou]/, '*')              #-> "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>')         #-> "h<e>ll<o>"
"hello".gsub(/./) {|s| s[0].to_s + ' '}   #-> "104 101 108 108 111 "
Информация

Полезно посмотреть на метод sub, который имеет схожую функциональность

String#gsub![править]


str.gsub!(pattern, replacement)        #-> str или nil
str.gsub!(pattern) {|match| block }    #-> str или nil

Выполняет замены подобно gsub, но изменяет исходную строку str. Возвращает результат замен или nil, если замены невозможны.

Информация

Полезно посмотреть на метод sub!, который имеет схожую функциональность

String#hash[править]


str.hash   #-> fixnum

Вычисляет хеш-код для строки str. Две строки с одним и тем же содержимым будут иметь одинаковый хеш-код (именно его использует метод eql?).

"rubynovich".hash   #-> 958124529

String#hex[править]


str.hex   #-> integer

Трактует строку str как строку шестнадцатиричных цифр (с необязательным указанием знака или необятельным префиксом 0x) и возвращает cоотвествующее число. Если преобразование не удается, то возвращает ноль.

"0x0a".hex     #-> 10
"-1234".hex    #-> -4660
"0".hex        #-> 0
"wombat".hex   #-> 0
Информация
  • Вместо данного метода рекомендуется использовать метод to_i, который является универсальной заменой методов hex и oct
  • Полезно взглянуть на метод oct, который имеет схожий функционал

String#include?[править]


str.include? other_str   #-> true или false
str.include? fixnum      #-> true или false

Возвращает true, если строка str содержит передаваемые параметром строку other_str или символ fixnum.

"hello".include? "lo"   #-> true
"hello".include? "ol"   #-> false
"hello".include? ?h     #-> true

String#index[править]


str.index(substring [, offset])   #-> fixnum или nil
str.index(fixnum [, offset])      #-> fixnum или nil
str.index(regexp [, offset])      #-> fixnum или nil

Возвращает индекс первого вхождения передаваемой параметром подстроки (substring), символа (fixnum) или совпадения с правилом (regexp) в строке str. Возвращает nil, если вхождения нет. В качестве второго параметра передается индекс (offset), с которого следует начинать поиск вхождений.

"hello".index('e')             #-> 1
"hello".index('lo')            #-> 3
"hello".index('a')             #-> nil
"hello".index(10)             #-> 1
"hello".index(/[aeiou]/, -3)   #-> 4
Информация

Полезно также взглянуть на метод rindex, который имеет подобный функционал

String#insert[править]


str.insert(index, other_str)   #-> str

Вставляет строку other_str после указанного индекса index в строку str. Отрицательная индексация подразумевает нумерацию с конца строки.

"abcd".insert(0, 'X')    #-> "Xabcd"
"abcd".insert(3, 'X')    #-> "abcXd"
"abcd".insert(4, 'X')    #-> "abcdX"
"abcd".insert(-3, 'X')   #-> "abXcd"
"abcd".insert(-1, 'X')   #-> "abcdX"

String#inspect[править]


str.inspect   #-> string

Возвращает печатную версию строки str, в которой все специальные символы экранированы.

str = "hello"
str[3] = 8
str.inspect       #-> "hel\010o"

String#intern[править]


str.intern   #-> symbol
str.to_sym   #-> symbol

Возвращает объект класса Symbol, который соответствует строке str.

"Koala".intern         #-> :Koala
s = 'cat'.intern       #-> :cat
s == :cat              #-> true
s = '@cat'.intern      #-> :@cat
s == :@cat             #-> true

Этот метод может быть использован для создания символов, которые не могут быть созданы в :xxx нотации.

'cat and dog'.intern   #-> :"cat and dog"
Информация
  • Полезно также взглянуть на метод Symbol#id2name, который осуществляет обратное преобразование
  • Методы intern и to_sym — абсолютно идентичны, но использование метода to_sym предпочтительнее

String#length[править]


str.length   #-> integer
str.size     #-> integer

Возвращает размер строки str.

string = "54321"
string.length   #-> 5
Информация

Методы size и length — абсолютно идентичны, то есть являются именами одного и того же метода

String#ljust[править]


str.ljust(integer, padstr=' ')   #-> new_str

Если параметр integer больше, чем длина строки str, то возвращается новая строка длины integer со строкой str, которая выравнена по левому краю, а возникшее пустое место заполняется символами padstr; иначе, возвращается строка str.

"hello".ljust(4)            #-> "hello"
"hello".ljust(20)           #-> "hello               "
"hello".ljust(20, '1234')   #-> "hello123412341234123"
Информация

Полезно посмотреть на методы rjust и center, которые имеют схожую функциональность

String#lstrip[править]


str.lstrip   #-> new_str

Возвращает копию строки str, в которой удалены все ведущие пробельные символы.

"  hello  ".lstrip   #-> "hello  "
"hello".lstrip       #-> "hello"
Информация

Полезно посмотреть на методы rstrip и strip, которые имеют схожую функциональность

String#lstrip![править]


str.lstrip!   #-> self или nil

Удаляет ведущие пробелы из строки str. Возвращает nil, если в результате работы метода строка str осталась неизменной.

"  hello  ".lstrip   #-> "hello  "
"hello".lstrip!      #-> nil
Информация

Полезно посмотреть на методы rstrip! и strip!, которые имеют схожую функциональность

String#match[править]


str.match(pattern)   #-> matchdata или nil

Преобразует параметр pattern в правило (если он таковым не был) и осуществляет сопоставление этого правила со строкой str.

'hello'.match('(.)\1')      #-> #<MatchData:0x401b3d30>
'hello'.match('(.)\1')[0]   #-> "ll"
'hello'.match(/(.)\1/)[0]   #-> "ll"
'hello'.match('xx')         #-> nil
Информация

Данный метод практически не используется разработчиками. Вместо него рекомендуется использовать метод [] («батарейка»), который обладает схожим, но более развернутым функционалом

String#next[править]


str.succ   #-> new_str
str.next   #-> new_str

Рассматривает строку str как элемент символьной последовательности и возвращает следующий за строкой str элемент. Следующий элемент вычисляется увеличением кода крайнего правого элемента строки str на единицу. В результате увеличения символа, который является цифрой — получится цифра, а для символа, который является буквой — буква. Увеличение остальных символов происходит с использованием базовой символьной упорядоченной последовательности.

Если в результате увеличения возникает необходимость «переноса», символ левее увеличиваемого в данный момент — тоже увеличивается. Этот процесс повторяется для всех требуемых «переносов». Если необходимо, то к строке str будет добавлен дополнительный символ.

"abcd".next        #-> "abce"
"THX1138".next     #-> "THX1139"
"<<koala>>".next   #-> "<<koalb>>"
"1999zzz".next     #-> "2000aaa"
"ZZZ9999".next     #-> "AAAA0000"
"***".next         #-> "**+"
"zzz".next         #-> "aaaa"
Информация

Методы next и succ — абсолютно идентичны, то есть являются именами одного и того же метода

String#next![править]


str.succ!   #-> str
str.next!   #-> str

Эквивалентен методу next, но меняет строку str на результат своей работы.

Информация

Методы next! и succ! — абсолютно идентичны, то есть являются именами одного и того же метода

String#oct[править]


str.oct   #-> integer

Трактует строку str как строку восьмеричных цифр (с необязательным указанием знака или необятельным префиксом 0) и возвращает cоотвествующее число. Если преобразование не удается, то возвращает ноль.

"123".oct       #-> 83
"-377".oct      #-> -255
"bad".oct       #-> 0
"0377bad".oct   #-> 255
Информация
  • Вместо данного метода рекомендуется использовать метод to_i, который является универсальной заменой методов hex и oct
  • Полезно взглянуть на метод hex, который имеет схожий функционал

String#ord[править]


str.ord   #-> integer

Возвращает целочисленный порядковый номер строки из одного символа.


"a".ord       #-> 97
"A".ord      #-> 65
"z".ord      #-> 90
"Z".ord      #-> 122
Информация

Обратите внимание, что метод правильно работает при возврате порядкового номера при исползовании метода swapcase

String#partition[править]


str.partition(sep)  #-> [head, sep, tail]
str.partition(regexp) #-> [head, match, tail]

Ищет sep или шаблон (regexp) в строке и возвращает часть перед ним, совпадение и часть после него. Если он не найден, возвращает две пустые строки и строку.


"hello".partition("l")         #=> ["he", "l", "lo"]
"hello".partition("x")         #=> ["hello", "", ""]
"hello".partition(/.l/)        #=> ["h", "el", "lo"]

String#replace[править]


str.replace   #-> str

Заменяет содержимое str соответствующими значениями из other_str.


s = "krishna"       #-> "krishna"
s.replace "rama"      #-> "rama"

String#reverse[править]


str.reverse   #-> new_str

Возвращает новую строку, в которой символы строки str переставлены в обратном порядке.

"stressed".reverse   #-> "desserts"

String#reverse![править]


str.reverse!   #-> str

Изменяет порядок символов строки str на обратный.

str="stressed"
str.reverse!   #-> "desserts"
str            #-> "desserts"
Информация

Обратите внимание, что ни при каких обстоятельствах метод reverse! не возвращает nil

String#rindex[править]


str.rindex(substring [, fixnum])   #-> fixnum или nil
str.rindex(fixnum [, fixnum])      #-> fixnum или nil
str.rindex(regexp [, fixnum])      #-> fixnum или nil

Возвращает индекс последнего вхождения передаваемой параметром подстроки (substring), символа (fixnum) или совпадения с правилом (regexp) в строке str. Возвращает nil, если вхождения нет. В качестве второго параметра передается индекс (fixnum), на котором следует закончить поиск.

"hello".rindex('e')             #-> 1
"hello".rindex('l')             #-> 3
"hello".rindex('a')             #-> nil
"hello".rindex(101)             #-> 1
"hello".rindex(/[aeiou]/, -2)   #-> 1
Информация

Полезно посмотреть на метод index, который имеет схожую функциональность

String#rjust[править]


str.rjust(integer, padstr=' ')   #-> new_str

Если параметр integer больше, чем длина строки str, то метод возвращает новую строку длины integer со строкой str выравненной по правому краю, а возникшее пустое место заполняется символами padstr; иначе, возвращается строка str.

"hello".rjust(4)            #-> "hello"
"hello".rjust(20)           #-> "               hello"
"hello".rjust(20, '1234')   #-> "123412341234123hello"
Информация

Полезно посмотреть на методы ljust и center, которые имеют схожую функциональность

String#rstrip[править]


str.rstrip   #-> new_str

Возвращает копию строки str, в которой удалены все замыкающие пробельные символы.

"  hello  ".rstrip   #-> "  hello"
"hello".rstrip       #-> "hello"
Информация

Следует обратить внимание на методы lstrip и strip, которые имеют схожую функциональность

String#rstrip![править]


str.rstrip!   #-> self или nil

Удаляет замыкающие пробельные символы из строки str. Возвращает nil, если в результате работы метода никаких изменений сделано не было.

"  hello  ".rstrip   #-> "  hello"
"hello".rstrip!      #-> nil
Информация

Полезно посмотреть описание методов lstrip! и strip!, которые имеют схожую функциональность

String#scan[править]


str.scan(pattern)                         #-> array
str.scan(pattern) {|match, ...| block }   #-> str

Обе формы вызова последовательно просматривают str на предмет совпадения с шаблоном (который может быть как строкой, так и правилом. Каждое совпадение записывается в массив (для первой формы вызова) или передается в блок (для второй формы вызова). Если шаблон (который является правилом) не содержит группировок, то каждое совпадение записывается в отдельный элемент (для первой формы вызова) или передается параметром блоку (для второй формы вызова). Также возможно использование специальной переменной $&, которая содержит результат последнего совпадения (актуально при использовании второй формы вызова). Если шаблон содержит группировки, то каждое совпадение разбивается на совпадения группировкам (получается двумерный массив).

a = "cruel world"
a.scan(/\w+/)        #-> ["cruel", "world"]
a.scan(/.../)        #-> ["cru", "el ", "wor"]
a.scan(/(...)/)      #-> [["cru"], ["el "], ["wor"]]
a.scan(/(..)(..)/)   #-> [["cr", "ue"], ["l ", "wo"]]

…и для второй формы вызова:

a.scan(/\w+/) {|w| print "<<#{w}>> " }
print "\n"
a.scan(/(.)(.)/) {|a,b| print b, a }
print "\n"

результат:

 <<cruel>> <<world>>
 rceu lowlr
Информация

Полезно посмотреть на метод split, который имеет схожую функциональность

String#setbyte[править]


str.setbyte(index, integer)  # => integer

Заменяет содержимое str соответствующими значениями из other_str.

s = "Sunday"
s.setbyte(0, 77)
s.setbyte(-5, 111)
s # => "Monday"

String#size[править]


str.length   #-> integer
str.size     #-> integer

Возвращает размер строки str.

string = "54321"
string.size   #-> 5
Информация

Методы size и length — абсолютно идентичны, то есть являются именами одного и того же метода

String#slice[править]


str[index]                 #-> fixnum или nil
str[start, length]         #-> new_str или nil
str[range]                 #-> new_str или nil
str[regexp]                #-> new_str или nil
str[regexp, index]         #-> new_str или nil
str[other_str]             #-> new_str или nil
str.slice(index)           #-> fixnum или nil
str.slice(start, length)   #-> new_str или nil
str.slice(range)           #-> new_str или nil
str.slice(regexp)          #-> new_str или nil
str.slice(regexp, index)   #-> new_str или nil
str.slice(other_str)       #-> new_str или nil

Получение подстроки или символа — возвращает код символа с индексом index, или подстроку длины length, начиная с индекса start, или подстроку, которая располагается в диапазоне range. Во всех этих вариантах вызова отрицательная индексация подразумевает отсчет с конца строки str. Возвращается nil, если индекс index выходит за пределы допустимого диапазона, размер length запрашиваемой подстроки отрицательный или начало диапазона range попадает после конца строки str. Если передается правило regexp, то возвращается фрагмент строки str, который удовлетворяет правилу regexp (или nil, если такого совпадения найти не удалось). Если задан дополнительный параметр index, то возвращается содержимое группировки правила с номером index (если index равен 0, то возвращается фрагмент строки, который удовлетворяет правилу regexp). Если в качестве аргумента передается строка other_str, то возвращается строка other_str, если она является подстрокой строки str (или nil, иначе).

a = "hello there"
a.slice(1)                   #-> "e"
a.slice(1,3)                 #-> "ell"
a.slice(1..3)                #-> "ell"
a.slice(-3,2)                #-> "er"
a.slice(-4..-2)              #-> "her"
a.slice(12..-1)              #-> nil
a.slice(-2..-4)              #-> ""
a.slice(/[aeiou](.)\1/)      #-> "ell"
a.slice(/[aeiou](.)\1/, 0)   #-> "ell"
a.slice(/[aeiou](.)\1/, 1)   #-> "l"
a.slice(/[aeiou](.)\1/, 2)   #-> nil
a.slice("lo")                #-> "lo"
a.slice("bye")               #-> nil
Информация

Методы slice и [] («батарейка») — абсолютно идентичны!

String#slice![править]


str.slice!(fixnum)           #-> fixnum или nil
str.slice!(fixnum, fixnum)   #-> new_str или nil
str.slice!(range)            #-> new_str или nil
str.slice!(regexp)           #-> new_str или nil
str.slice!(other_str)        #-> new_str или nil

Удаляет определенный кусок текста из строки str и возвращает этот кусок в качестве результата. Если в качестве параметра передается число (Fixnum), то возможно возникновение ошибки типа IndexError, когда значение этого числа находится вне допустимого диапазона. Если в качестве параметра передается диапазон (Range), то возможно возникновение ошибки типа RangeError, когда диапазон выходит за рамки допустимых значений. В случае с параметрами типа Regexp и String метод молча реагирует на недопустимые значения.

string = "this is a string"
string.slice!(2)        #-> "i"
string.slice!(3..6)     #-> " is "
string.slice!(/s.*t/)   #-> "sa st"
string.slice!("r")      #-> "r"
string                  #-> "thing"
Информация

Полезно посмотреть на методы slice и [] («батарейка»), которые имеют подобную функциональность

String#split[править]


str.split(pattern=$;, [limit])   #-> anArray

Делит строку str на подстроки по разделителю pattern (который может быть как правилом, так и строкой). Если разделитель pattern не указан, то деление происходит по пробельному символу (если иное не присвоено специальной переменной $;). В результате деления возвращается массив, который содержит фрагменты строки str (сам разделитель в результат не входит).

Если разделитель pattern является правилом, то деление производится по подстрокам, подходящим под данное правило. Если pattern — строка, то деление производится по подстрокам, которые совпадают с разделителем.

Если задан необязательный параметр limit, то результирующий массив будет иметь количество фрагментов строки str равное limit. Последний элемент будет содержать остаток, который, возможно, еще можно поделить (то есть в строке есть еще разделители).

" now's  the time".split        #-> ["now's", "the", "time"]
" now's  the time".split(' ')   #-> ["now's", "the", "time"]
" now's  the time".split(/ /)   #-> ["", "now's", "", "the", "time"]
"1, 2.34,56, 7".split(%r{,\s*}) #-> ["1", "2.34", "56", "7"]
"hello".split(//)               #-> ["h", "e", "l", "l", "o"]
"hello".split(//, 3)            #-> ["h", "e", "llo"]
"hi mom".split(%r{\s*})         #-> ["h", "i", "m", "o", "m"]

"mellow yellow".split("ello")   #-> ["m", "w y", "w"]
"1,2,,3,4,,".split(',')         #-> ["1", "2", "", "3", "4"]
"1,2,,3,4,,".split(',', 4)      #-> ["1", "2", "", "3,4,,"]
"1,2,,3,4,,".split(',', -4)     #-> ["1", "2", "", "3", "4", "", ""]
"1:2:3".split(/(:)()()/, 2)     #=> ["1", ":", "", "", "2:3"]
"".split(',', -1)               #=> []
Информация

Полезно посмотреть на методы scan и chars, которые имеют схожую функциональность

String#squeeze[править]


str.squeeze(del=nil)    #-> new_str

Создает множество символов из строки (или строк) del, переданных в качестве параметра. Возвращает новую строку, где идущие подряд одинаковые символы, которые принадлежат множеству (переданному в качестве параметра), заменяются на один такой символ. Если метод вызван без параметра, то все идущие подряд повторяющиеся символы будут заменены на соответствующий единичный.

"yellow moon".squeeze                  #-> "yelow mon"
"  now   is  the".squeeze(" ")         #-> " now is the"
"putters shoot balls".squeeze("m-z")   #-> "puters shot balls"
Информация

Использует те же самые правила создания множеств символов, что и в методе count

String#squeeze![править]


str.squeeze!(del=nil)    #-> new_str

Работает точно также, как и метод squeeze, но результат своей работы записывает в исходную строку.

str = "yellow moon"
str.squeeze! #-> "yelow mon"
str          #-> "yelow mon

String#start_with?[править]


str.start_with?([prefixes]+) #-> true или false

Возвращает true, если str начинается с одного из заданных префиксов. Каждый из префиксов должен быть строкой или шаблоном (рegexp).

"hello".start_with?("hell")               #=> true
"hello".start_with?(/H/i)                 #=> true

Возвращает истину, если один из префиксов совпадает.

"hello".start_with?("heaven", "hell")     #=> true
"hello".start_with?("heaven", "paradise") #=> false

String#strip[править]


str.strip   #-> new_str

Возвращает копию строки str в которой удалены ведущие и замыкающие пробельные символы.

"    hello    ".strip   #-> "hello"
"\tgoodbye\r\n".strip   #-> "goodbye"
Информация

Полезно посмотреть на методы lstrip и rstrip, которые имеют схожую функциональность

String#strip![править]


str.strip!   #-> str или nil

Удаляет ведущие и замыкающие пробельные символы из строки str. Возвращает nil, если строка str таковых не содержит.

str = "    hello    "
str.strip!        #-> "hello"
str               #-> "hello"
"goodbye".strip   #-> nil
Информация

Полезно посмотреть на методы lstrip! и rstrip!, которые имеют схожую функциональность

String#sub[править]


str.sub(pattern, replacement)         #-> new_str
str.sub(pattern) {|match| block }     #-> new_str

Возвращает копию строки str, где первое совпадение с шаблоном (или строкой) pattern заменено на строку replacement или результат выполнения блока (которому передается параметром результат совпадения).

В результате работы метода, найденное совпадение с шаблоном pattern записывается в специальную переменную $& (наследие языка Perl). В строке replacement возможно использование последовательностей вида \1, \2 и так далее до \9, которые являются ссылками на совпадения с группировками (номер группировки считается слева направо). Внутри блока на группировки можно ссылаться при помощи специальных переменных вида $1, $2 и так далее до $9. Также, выражению в блоке доступны специальные переменные $`, $& и $', которые позволяют получить доступ к подстроке до совпадения, совпадению и подстроке после совпадения, соответственно.

"hello".sub(/[aeiou]/, '*')               #-> "h*llo"
"hello".sub(/([aeiou])/, '<\1>')          #-> "h<e>llo"
"hello".sub(/./) {|s| s[0].to_s + ' ' }   #-> "104 ello"
Информация

Полезно посмотреть на метод gsub, который имеет схожую функциональность

String#sub![править]


str.sub!(pattern, replacement)          #-> str или nil
str.sub!(pattern) {|match| block }      #-> str или nil

Выполняет замену подобно sub, но изменяет исходную строку str. Возвращает результат замены или nil, если замена невозможна.

Информация

Полезно посмотреть на метод gsub!, который имеет схожую функциональность

String#succ[править]


str.succ   #-> new_str
str.next   #-> new_str

Рассматривает строку str как элемент символьной последовательности и возвращает следующий за строкой str элемент. Следующий элемент вычисляется увеличением кода крайнего правого элемента строки str на единицу. В результате увеличения символа, который является цифрой — получится цифра, а для символа, который является буквой — буква. Увеличение остальных символов происходит с использованием базовой символьной упорядоченной последовательности. Если в результате увеличения возникает необходимость «переноса», символ левее увеличиваемого в данный момент — тоже увеличивается. Этот процесс повторяется для всех требуемых «переносов». Если необходимо, то к строке str будет добавлен дополнительный символ.

"abcd".succ        #-> "abce"
"THX1138".succ     #-> "THX1139"
"<<koala>>".succ   #-> "<<koalb>>"
"1999zzz".succ     #-> "2000aaa"
"ZZZ9999".succ     #-> "AAAA0000"
"***".succ         #-> "**+"
"zzz".succ         #-> "aaaa"
Информация

Методы succ и next — абсолютно идентичны, то есть являются именами одного и того же метода

String#succ![править]


str.succ!   #-> str
str.next!   #-> str

Эквивалентен методу succ, но меняет строку str на результат своей работы.

Информация

Методы succ! и next! — абсолютно идентичны, то есть являются именами одного и того же метода

String#sum[править]


str.sum(n=16)   #-> integer

Возвращает простую n-битную контрольную сумму символов строки str, где n опциональный целочисленный (Fixnum) параметр, по-умолчанию равный 16. Результатом -- это просто суммирование двоичных значений каждого символа строки str по модулю 2n - 1.

String#swapcase[править]


str.swapcase   #-> new_str

Возвращает копию строки str в которой все символы нижнего регистра заменены на соответствующие символы верхнего и все символы верхнего регистра заменены на соответствующие символы нижнего.

"Hello".swapcase           #-> "hELLO"
"cYbEr_PuNk11".swapcase   #-> "CyBeR_pUnK11"
Информация
  • В переводе с английского, «swap» — переставлять местами
  • Полезно посмотреть методы capitalize, downcase и upcase, которые также производят преобразования регистра

String#swapcase![править]


str.swapcase!   #-> str или nil

Модифицирует строку str по правилу: все символы нижнего регистра заменены на соответствующие символы верхнего и все символы верхнего регистра заменены на соответствующие символы нижнего. Возвращает nil, если изменения не требуются.

str="Hello"
str.swapcase!          #-> "hELLO"
str                    #-> "hELLO"
str.swapcase!          #-> "Hello"
"12345".swapcase!      #-> nil
Информация
  • В переводе с английского, «swap» — переставлять местами
  • Полезно посмотреть методы capitalize!, downcase! и upcase!, которые также производят преобразования регистра


String#to_a[править]


str.to_a()   #-> array

String#to_c[править]


str.to_c   #-> complex

Возвращает комплексные числа complex, обозначающие строковую форму. Парсер игнорирует начальные пробелы и мусор в конце. Любые последовательности цифр можно разделить знаком подчеркивания. Возвращает nil для нулевой или мусорной строки.

'9'.to_c           #=> (9+0i)
'2.5'.to_c         #=> (2.5+0i)
'2.5/1'.to_c       #=> ((5/2)+0i)
'-3/2'.to_c        #=> ((-3/2)+0i)
'-i'.to_c          #=> (0-1i)
'45i'.to_c         #=> (0+45i)
'3-4i'.to_c        #=> (3-4i)
'-4e2-4e-2i'.to_c  #=> (-400.0-0.04i)
'-0.0-0.0i'.to_c   #=> (-0.0-0.0i)
'1/2+3/4i'.to_c    #=> ((1/2)+(3/4)*i)
'ruby'.to_c        #=> (0+0i)
Информация

Подробнее смотрите: Complex

String#to_f[править]


str.to_f   #-> float

Возвращает результат интерпретации строки str, как дробного числа. Символы после последнего числового — игнорируются. Если строка str не является дробным числом, то возвращается 0.0.

"123.45e1".to_f        #-> 1234.5
"45.67 degrees".to_f   #-> 45.67
"thx1138".to_f         #-> 0.0
Информация

Полезно посмотреть на метод to_i, который имеет схожую функциональность

Информация

Данный метод относится к отряду «тихих» методов, то есть не порождающих ошибок в результате своей работы

String#to_i[править]


str.to_i(base=10)   #-> integer

Возвращает в качестве результата интерпретацию символов строки str, как целого числа с основанием base (2, 8, 10, 16 или любого другого). Символы после последнего числового — игнорируются. Если строка str не является числом, то возвращается 0.

"12345".to_i             #-> 12345
"99 red balloons".to_i   #-> 99
"0a".to_i                #-> 0
"0a".to_i(16)            #-> 10
"hello".to_i             #-> 0
"1100101".to_i(2)        #-> 101
"1100101".to_i(8)        #-> 294977
"1100101".to_i(10)       #-> 1100101
"1100101".to_i(16)       #-> 17826049
Информация

Данный метод относится к отряду «тихих» методов, то есть не порождающих ошибок в результате своей работы

String#to_s[править]


str.to_s     #-> str
str.to_str   #-> str

Возвращает строку str в качестве результата. Никаких преобразований не производится.

Информация

Методы to_s и to_str — абсолютно идентичны, но использование метода to_s предпочтительнее, так как его название короче

String#to_str[править]


str.to_s     #-> str
str.to_str   #-> str

Возвращает строку str в качестве результата. Никаких преобразований не производится.

Информация

Методы to_s и to_str — абсолютно идентичны, но использование метода to_s предпочтительнее, так как его название короче

String#to_sym[править]


str.intern   #-> symbol
str.to_sym   #-> symbol

Возвращает объект класса Symbol, который соответствует строке str.

"Koala".to_sym         #-> :Koala
s = 'cat'.to_sym       #-> :cat
s == :cat              #-> true
s = '@cat'.to_sym      #-> :@cat
s == :@cat             #-> true

Этот метод может быть использован для создания символов, которые не могут быть созданы в :xxx нотации.

'cat and dog'.to_sym   #-> :"cat and dog"
Информация
  • Полезно также взглянуть на метод Symbol#id2name, который осуществляет обратное преобразование
  • Методы intern и to_sym — абсолютно идентичны, но использование метода to_sym предпочтительнее

String#tr[править]


str.tr(from, to)  #-> new_str

Возвращает копию строки str в которой символы из строки from заменены на соответствующие символы из строки to. Если строка to короче, чем from, то строка дополняется своим последним символом до длины строки from. Оба строковых параметра (from и to) могут использовать нотацию c1-c2, которая разворачивается в последовательность символов в диапазоне от с1 до с2. Если первым символом в строковом параметре указать символ ^, то это будет означать все множество символов, кроме указанных.

"hello".tr('aeiou', '*')   #-> "h*ll*"  
"hello".tr('^aeiou', '*')  #-> "*e**o"  
"hello".tr('el', 'ip')     #-> "hippo"  
"hello".tr('a-y', 'b-z')   #-> "ifmmp"
Информация

Полезно посмотреть на метод tr_s, который имеет схожую функциональность

String#tr![править]


str.tr!(from, to)  #-> new_str или nil

Преобразует строку str, используя алгоритм, описанный для метода tr. Возвращает результат преобразования или nil, если в результате работы метода изменений сделано не было.

Информация

Полезно посмотреть на метод tr_s!, который имеет схожую функциональность

String#tr_s[править]


str.tr_s(from, to)   #-> new_str

Создает копию строки str, которая преобразована по алгоритму, описанному в методе tr, но с предварительным удалением дубликатов символов, которые описаны в строке from.

"hello".tr_s('l', 'r')     #-> "hero"
"hello".tr_s('el', '*')    #-> "h*o"
"hello".tr_s('el', 'hx')   #-> "hhxo"
Информация

Полезно посмотреть на метод tr, который имеет схожую функциональность

String#tr_s![править]


str.tr_s!(from, to)  #-> new_str или nil

Преобразует строку str по алгоритму описанному в методе tr_s. Возвращает результат преобразования или nil, если в результате работы метода преобразований сделано не было.

Информация

Полезно посмотреть на метод tr!, который имеет схожую функциональность

String#unpack[править]


str.unpack(format)   #-> anArray

Декодирует строку str (которая может содержать двоичные данные) в соответствии с опциями, заданными в строке format и возвращает массив с декодированными данными. Строка format состоит из односимвольных директив (см. таблицу ниже). За каждой директивой может следовать число, которое описывает количество повторений этой опции. Символ «звездочка» (*) применяет опцию ко всем элементам строки (как бы бесконечное количество повторений опции). После директив s, S, i, I, l и L может следовать символ подчеркивания(_), который позволяет использовать размеры типов (количество бит), которые специфичны для данной платформы; иначе, будут использоваться платформо-независимые размеры типов. Пробельные символы в строке format игнорируются.

"abc \0\0abc \0\0".unpack('A6Z6')   #-> ["abc", "abc "]
"abc \0\0".unpack('a3a3')           #-> ["abc", " \000\000"]
"abc \0abc \0".unpack('Z*Z*')       #-> ["abc ", "abc "]
"aa".unpack('b8B8')                 #-> ["10000110", "01100001"]
"aaa".unpack('h2H2c')               #-> ["16", "61", 97]
"\xfe\xff\xfe\xff".unpack('sS')     #-> [-2, 65534]
"now=20is".unpack('M*')             #-> ["now is"]
"whole".unpack('xax2aX2aX1aX2a')    #-> ["h", "e", "l", "l", "o"]
Опция Тип Описание
A
String
строка с удаленными замыкающими пробельными символами
a
String
строка
B
String
извлечь биты из каждого символа (старший двоичный разряд идет первым)
b
String
извлечь биты из каждого символа (младший двоичный разряд идет первым)
C
Fixnum
извлечь символ, как беззнаковое целое (unsigned int)
c
Fixnum
извлечь символ, как целое (int)
d, D
Float
интерпретировать sizeof(double) символов как дробное двойной точности (double), собственный формат («нативный»)
E
Float
интерпретировать sizeof(double) символов как дробное двойной точности (double), прямой порядок байт
e
Float
интерпретировать sizeof(float) символов как дробное (float), прямой порядок байт
f, F
Float
интерпретировать sizeof(float) символов как дробное (float), собственный формат («нативный»)
G
Float
интерпретировать sizeof(double) символов как дробное с двойной точностью (double), «сетевой» порядок байт
g
Float
интерпретировать sizeof(float) символов как дробное (float), «сетевой» порядок байт
H
String
извлечь шестнадцатиричные полубайты из каждого символа (старший полубайт идет первым)
h
String
извлечь шестнадцатиричные полубайты из каждого символа (младший полубайт идет первым)
I
Integer
интерпретировать sizeof(int) (может отличаться, если используется _) следующих символов как беззнаковое целое (unsigned int), собственный формат («нативный»)
i
Integer
интерпретировать sizeof(int) (может отличаться, если используется _) следующих символов как целое (int), собственный формат («нативный»)
L
Integer
интерпретировать четыре (может отличаться, если используется _) следующих символа как беззнаковое длинное целое (unsigned long int), собственный формат («нативный»)
l
Integer
интерпретировать четыре (может отличаться, если используется _) следующих символа как длинное целое (long int), собственный формат («нативный»)
M
String
строка готовая к печати, закодированная MIME (см. RFC2045)
m
String
строка закодированная Base64 (см. RFC4648)
N
Integer
интерпретировать четыре символа как беззнаковое длинное целое (unsigned long int), «сетевой» порядок байт
n
Fixnum
интерпретировать два символа как беззнаковое короткое целое (unsigned short int), «сетевой» порядок байт
P
String
интерпретировать sizeof(char *) символов как указатель и вернуть \emph{len} символов из указанной области
p
String
интерпретировать sizeof(char *) символов как указатель на строку с завершающим нулем
Q
Integer
интерпретировать 8 символов как беззнаковое 64-битное целое
q
Integer
интерпретировать 8 символов как 64-битное целое
S
Fixnum
интерпретировать два (количество может отличаться, если используется _) следующих символа как беззнаковое короткое целое (unsigned short int), собственный формат («нативный»)
s
Fixnum
интерпретировать два (количество может отличаться, если используется _) следующих символа как короткое целое (short int), собственный формат («нативный»)
U
Integer
UTF-8 символы как беззнаковое целое
u
String
строка UU-кодированная
V
Fixnum
интерпретировать четыре символа как беззнаковое длинное целое (unsigned long int), прямой порядок байт
v
Fixnum
интерпретировать два символа как беззнаковое короткое целое (unsigned short int), прямой порядок байт
w
Integer
BER-упакованное целое (см. Array.pack)
X
переместить указатель на один символ назад
x
переместить указатель на один символ вперед
Z
String
строка с удаленными замыкающими нулевыми символами (null) до первого null с *
@
переместить указатель на абсолютную позицию
Информация

Полезно посмотреть на метод pack, который имеет схожую функциональность

String#upcase[править]


str.upcase   #-> new_str

Возвращает копию строки str в которой все символы нижнего регистра заменены на соответствующие символы верхнего.

"hEllO".upcase    #-> "HELLO"
Информация

Полезно посмотреть на методы capitalize, downcase и swapcase, которые имеют схожую функциональность

String#upcase![править]


str.upcase!   #-> str или nil

Модифицирует строку str по правилу: все символы нижнего регистра преобразовываются в соответствующие символы верхнего. Возвращает nil, если изменения не требуются.

str="hEllO"
str.upcase!    #-> "HELLO"
str            #-> "HELLO"
str.upcase!    #-> nil
Информация

Полезно посмотреть на методы capitalize!, downcase! и swapcase!, которые имеют схожую функциональность

String#upto[править]


str.upto(other_str) {|s| block }   #-> str

Данный итератор проходит все значения между str и other_str включительно, передавая их в блок в качестве параметра.

"a8".upto("b6") {|s| print s, ' ' }
for s in "a8".."b6"
  print s, ' '
end

результат:

 a8 a9 b0 b1 b2 b3 b4 b5 b6
 a8 a9 b0 b1 b2 b3 b4 b5 b6
Информация
  • Для поиска следующего значения последовательности используется метод succ
  • В качестве результата возвращает строку str (от которой был вызван)

String#valid_encoding?[править]


str.valid_encoding?   #-> true или false

Возвращает true для строки str, которая закодирована правильно.

"\xc2\xa1".force_encoding("UTF-8").valid_encoding?  #=> true
"\xc2".force_encoding("UTF-8").valid_encoding?      #=> false
"\x80".force_encoding("UTF-8").valid_encoding?      #=> false

Класс Struct[править]

Класс Struct реализует удобный способ объединения набора атрибутов, используя методы доступа, без явного создания класса. Класс Struct создает специфические классы, которые содержат только набор переменных и методы доступа к ним. В следующем примере мы создадим класс Customer и продемонстрируем пример использования объекта этого класса. В следующем описании, параметр symbol может быть строкой или экземпляром класса Symbol (например, :name).


Примеси

Enumerable (all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find, find_all, grep, group_by, include?, index_by, inject, map, max, member?, min, partition, reject, select, sort, sort_by, sum, to_a, to_set, zip)

Методы класса

new

Методы объекта

[]=, [], ==, each_pair, each, eql?, hash, inspect, length, members, select, size, to_a, to_s, values_at, values

Struct::new[править]


Struct.new( string, symbols* )    #-> StructClass
StructClass.new(arg, ...)         #-> obj
StructClass[arg, ...]             #-> obj

Создание нового класса с именем string, содержащего методы доступа к атрибутам. Если имя string пропущено, то будет создан анонимная структура. Иначе, имя этой структуры будет выглядеть как константа класса Struct. Учтите, что имя структуры должно быть уникально и начинаться с большой буквы. Struct::new возвращает объект класса Class, который может быть использован для создания специфичных экземпляров новой структуры. Число действительных параметров должно быть меньше или равно числу атрибутов, объявленных для этой структуры.

# Создание структуры с именем внутри класса Struct
Struct.new("Customer", :name, :address)    #-> Struct::Customer
Struct::Customer.new("Dave", "123 Main")   #-> #<Struct::Customer name="Dave", address="123 Main">

# Имя структуры зависит от имени константы
Customer = Struct.new(:name, :address)     #-> Customer
Customer.new("Dave", "123 Main")           #-> #<Customer name="Dave", address="123 Main">

Struct#==[править]


struct == other_struct     #-> true или false

Эквивалентность --- возвращает true если other_struct равен : они должны быть объектами одного и того же класса, созданного при помощи Struct::new, и значения внутренних переменных должны совпадать (в соответствии с методом Object#==).

Customer = Struct.new(:name, :address, :zip)
joe   = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
jane  = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)
joe == joejr   #-> true
joe == jane    #-> false

Struct#[][править]


struct[symbol]    #-> anObject
struct[fixnum]    #-> anObject

Значение атрибута можно получить, если передать в качестве параметра имя атрибута (в виде строки или символа) или числовой индекс в интервале (0..размер-1). Возникнет ошибка NameError, если имя атрибута отсутствует или IndexError, если числовой индекс будет лежать вне допустимого интервала.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe["name"]   #-> "Joe Smith"
joe[:name]    #-> "Joe Smith"
joe[0]        #-> "Joe Smith"

Struct#[]=[править]


struct[symbol] = obj    #-> obj
struct[fixnum] = obj    #-> obj

Изменить значение атрибута можно передав в качестве параметра имя атрибута (в виде строки или символа) или целочисленный индекс в интервале (0..размер-1), а также объект obj, который надо присвоить атрибуту. Возникнет ошибка NameError, если имени атрибута не существует или IndexError, если целочисленный индекс будет лежать вне диапазона.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe["name"] = "Luke"
joe[:zip]   = "90210"

joe.name   #-> "Luke"
joe.zip    #-> "90210"

Struct#each[править]


struct.each {|obj| block }  #-> struct

Выполняет block по разу на каждый атрибут, передавая в блок его значение.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joe.each {|x| puts(x) }

результат:

Joe Smith
123 Maple, Anytown NC
12345

Struct#each_pair[править]


struct.each_pair {|sym, obj| block }     #-> struct

Выполняет block по разу на каждый атрибут, передавая в блок имя (как символ) и значение параметра.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joe.each_pair {|name, value| puts("#{name} => #{value}") }

результат:

name => Joe Smith
address => 123 Maple, Anytown NC
zip => 12345

Struct#eql?[править]


struct.eql?(other)   #-> true или false

Две структуры эквивалентны, если они являются одним и тем же объектом или если все их атрибуты эквиваленты (используется метод eql?).

Struct#hash[править]


struct.hash   #-> fixnum

Возвращает контрольную сумму, основанную на контрольных суммах значений атрибутов.

Struct#inspect[править]


struct.to_s      #-> string
struct.inspect   #-> string

Демонстрирует содержимое структуры в виде строки.

(еще известен как to_s)

Struct#length[править]


struct.length    #-> fixnum
struct.size      #-> fixnum

Возвращает количество атрибутов структуры.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joe.length   #-> 3

(еще известен как size)

Struct#members[править]


struct.members    #-> array

Возвращает массив строк, состоящий из имен атрибутов структуры.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joe.members   #-> ["name", "address", "zip"]

Struct#select[править]


struct.select {|i| block }    #-> array

Выполняет блок для каждого значения атрибута в структуре, возвращает массив содержащий элементы для которых блок вернул значение true (эквивалент метода Enumerable#select).

Lots = Struct.new(:a, :b, :c, :d, :e, :f)
l = Lots.new(11, 22, 33, 44, 55, 66)
l.select {|v| (v % 2).zero? }   #-> [22, 44, 66]

Struct#size[править]


struct.length    #-> fixnum
struct.size      #-> fixnum

Возвращает количество атрибутов структуры.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joe.length   #-> 3

(еще известен как length :))

Struct#to_a[править]


struct.to_a     #-> array
struct.values   #-> array

Возвращает массив значений атрибутов структуры.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joe.to_a[1]   #-> "123 Maple, Anytown NC"

(еще известен как values)

Struct#to_s[править]


struct.to_s      #-> string
struct.inspect   #-> string

Демонстрирует содержимое структуры в виде строки.

(еще известен как inspect)

Struct#values[править]


struct.to_a     #-> array
struct.values   #-> array

Возвращает массив значений атрибутов структуры.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joe.to_a[1]   #-> "123 Maple, Anytown NC"

(еще известен как to_a)

Struct#values_at[править]


struct.values_at(selector,... )  #-> an_array

Возвращает массив, состоящий из значений элементов, индексы которых переданы в качестве параметров. Индексы могут быть целым числом или целочисленным интервалом. Смотри также select.

a = %w{ a b c d e f }
a.values_at(1, 3, 5)
a.values_at(1, 3, 5, 7)
a.values_at(-1, -3, -5, -7)
a.values_at(1..3, 2...5)

Класс Time[править]

Implements the extensions to the Time class that are described in the documentation for the time.rb library.


Extensions to time to allow comparisons with an early time class.


Примеси

Comparable (<, <=, ==, >, >=, between?)

Константы

CommonYearMonthDays, LeapYearMonthDays, MonthValue, RFC2822_DAY_NAME, RFC2822_MONTH_NAME, ZoneOffset

Методы класса

_load, apply_offset, at, gm, httpdate, local, make_time, mktime, month_days, new, now, parse, rfc2822, times, utc, w3cdtf, xmlschema, yaml_new, zone_offset, zone_utc?

Методы объекта

+, -, <=>, _dump, asctime, ctime, day, dst?, eql?, getgm, getlocal, getutc, gmt?, gmt_offset, gmtime, gmtoff, hash, hour, httpdate, inspect, isdst, iso8601, localtime, marshal_dump, marshal_load, mday, min, month, mon, rfc2822, rfc822, sec, strftime, succ, to_a, to_f, to_i, to_s, to_yaml, tv_sec, tv_usec, usec, utc?, utc_offset, utc, wday, xmlschema, yday, year, zone

Time::_load[править]


Time._load(string) #=> time

Unmarshal a dumped Time object.

Time::apply_offset[править]


Time::apply_offset(year, mon, day, hour, min, sec, off)

(нет описания...)

Time::at[править]


Time.at( aTime ) #=> time
Time.at( seconds [, microseconds] ) #=> time

Creates a new time object with the value given by aTime, or the given number of seconds (and optional microseconds) from epoch. A non-portable feature allows the offset to be negative on some systems.

Time.at(0)            #=> Wed Dec 31 18:00:00 CST 1969
Time.at(946702800)    #=> Fri Dec 31 23:00:00 CST 1999
Time.at(-284061600)   #=> Sat Dec 31 00:00:00 CST 1960

Time::gm[править]


 Time.utc( year [, month, day, hour, min, sec, usec] ) => time
 Time.utc( sec, min, hour, day, month, year, wday, yday, isdst, tz
 ) => time
 Time.gm( year [, month, day, hour, min, sec, usec] ) => time
 Time.gm( sec, min, hour, day, month, year, wday, yday, isdst, tz
 ) => time

Creates a time based on given values, interpreted as UTC (GMT). The year must be specified. Other values default to the minimum value for that field (and may be nil or omitted). Months may be specified by numbers from 1 to 12, or by the three-letter English month names. Hours are specified on a 24-hour clock (0..23). Raises an ArgumentError if any values are out of range. Will also accept ten arguments in the order output by Time#to_a.

  Time.utc(2000,"jan",1,20,15,1)  #=> Sat Jan 01 20:15:01 UTC 2000
  Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000

Time::httpdate[править]


 Time::httpdate(date)

Parses date as HTTP-date defined by RFC 2616 and converts it to a Time object. ArgumentError is raised if date is not compliant with RFC 2616 or Time class cannot represent specified date. See #httpdate for more information on this format.

Time::local[править]


 Time.local( year [, month, day, hour, min, sec, usec] ) => time
 Time.local( sec, min, hour, day, month, year, wday, yday, isdst,
 tz ) => time
 Time.mktime( year, month, day, hour, min, sec, usec )   => time

Same as Time::gm, but interprets the values in the local time zone.

  Time.local(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000

Time::make_time[править]


 Time::make_time(year, mon, day, hour, min, sec, sec_fraction, zone, now)

(нет описания...)

Time::mktime[править]


 Time.local( year [, month, day, hour, min, sec, usec] ) => time
 Time.local( sec, min, hour, day, month, year, wday, yday, isdst,
 tz ) => time
 Time.mktime( year, month, day, hour, min, sec, usec )   => time

Same as Time::gm, but interprets the values in the local time zone.

  Time.local(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000

Time::month_days[править]


 Time::month_days(y, m)

(нет описания...)

Time::new[править]


 Time.new -> time

Document-method: now Synonym for Time.new. Returns a Time object initialized to the current system time. Note: The object created will be created using the resolution available on your system clock, and so may include fractional seconds.

  a = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
  b = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
  a == b            #=> false
  "%.6f" % a.to_f   #=> "1049896563.230740"
  "%.6f" % b.to_f   #=> "1049896563.231466"

Time::now[править]


 Time.now -> time

Synonym for Time.new. Returns a Time object initialized to the current system time. Note: The object created will be created using the resolution available on your system clock, and so may include fractional seconds.

  a = Time.now      #=> Wed Apr 09 08:56:03 CDT 2003
  b = Time.now      #=> Wed Apr 09 08:56:03 CDT 2003
  a == b            #=> True
  "%.6f" % a.to_f   #=> "1049896563.230740"
  "%.6f" % b.to_f   #=> "1049896563.231466"

Time::parse[править]


 Time::parse(date, now=Time.now) {|year| ...}

Parses date using Date._parse and converts it to a Time object. If a block is given, the year described in date is converted by the block. For example:

   Time.parse(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}

If the upper components of the given time are broken or missing, they are supplied with those of now. For the lower components, the minimum values (1 or 0) are assumed if broken or missing. For example:

   # Suppose it is "Thu Nov 29 14:33:20 GMT 2001" now and
   # your timezone is GMT:
   Time.parse("16:30")     #=> Thu Nov 29 16:30:00 GMT 2001
   Time.parse("7/23")      #=> Mon Jul 23 00:00:00 GMT 2001
   Time.parse("Aug 31")    #=> Fri Aug 31 00:00:00 GMT 2001

Since there are numerous conflicts among locally defined timezone abbreviations all over the world, this method is not made to understand all of them. For example, the abbreviation "CST" is used variously as:

   -06:00 in America/Chicago,
   -05:00 in America/Havana,
   +08:00 in Asia/Harbin,
   +09:30 in Australia/Darwin,
   +10:30 in Australia/Adelaide,
   etc.

Based on the fact, this method only understands the timezone abbreviations described in RFC 822 and the system timezone, in the order named. (i.e. a definition in RFC 822 overrides the system timezone definition.) The system timezone is taken from Time.local(year, 1, 1).zone and Time.local(year, 7, 1).zone. If the extracted timezone abbreviation does not match any of them, it is ignored and the given time is regarded as a local time. ArgumentError is raised if Date._parse cannot extract information from date or Time class cannot represent specified date. This method can be used as fail-safe for other parsing methods as:

 Time.rfc2822(date) rescue Time.parse(date)
 Time.httpdate(date) rescue Time.parse(date)
 Time.xmlschema(date) rescue Time.parse(date)

A failure for Time.parse should be checked, though.

Time::rfc2822[править]


 Time::rfc2822(date)

Parses date as date-time defined by RFC 2822 and converts it to a Time object. The format is identical to the date format defined by RFC 822 and updated by RFC 1123. ArgumentError is raised if date is not compliant with RFC 2822 or Time class cannot represent specified date. See #rfc2822 for more information on this format.

Time::times[править]


 Time.times => struct_tms

Deprecated in favor of Process::times

Time::utc[править]


 Time.utc( year [, month, day, hour, min, sec, usec] ) => time
 Time.utc( sec, min, hour, day, month, year, wday, yday, isdst, tz
 ) => time
 Time.gm( year [, month, day, hour, min, sec, usec] ) => time
 Time.gm( sec, min, hour, day, month, year, wday, yday, isdst, tz
 ) => time

Creates a time based on given values, interpreted as UTC (GMT). The year must be specified. Other values default to the minimum value for that field (and may be nil or omitted). Months may be specified by numbers from 1 to 12, or by the three-letter English month names. Hours are specified on a 24-hour clock (0..23). Raises an ArgumentError if any values are out of range. Will also accept ten arguments in the order output by Time#to_a.

  Time.utc(2000,"jan",1,20,15,1)  #=> Sat Jan 01 20:15:01 UTC 2000
  Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000

Time::w3cdtf[править]


 Time::w3cdtf(date)

(нет описания...)

Time::xmlschema[править]


 Time::xmlschema(date)

Parses date as dateTime defined by XML Schema and converts it to a Time object. The format is restricted version of the format defined by ISO 8601. ArgumentError is raised if date is not compliant with the format or Time class cannot represent specified date. See #xmlschema for more information on this format.

Time::yaml_new[править]


 Time::yaml_new( klass, tag, val )

(нет описания...)

Time::zone_offset[править]


 Time::zone_offset(zone, year=Time.now.year)

(нет описания...)

Time::zone_utc?[править]


 Time::zone_utc?(zone)

(нет описания...)

Time#+[править]


 time + numeric => time

Addition---Adds some number of seconds (possibly fractional) to time and returns that value as a new time.

  t = Time.now         #=> Wed Apr 09 08:56:03 CDT 2003
  t + (60 * 60 * 24)   #=> Thu Apr 10 08:56:03 CDT 2003

Time#-[править]


 time - other_time => float
 time - numeric    => time

Difference---Returns a new time that represents the difference between two times, or subtracts the given number of seconds in numeric from time.

  t = Time.now       #=> Wed Apr 09 08:56:03 CDT 2003
  t2 = t + 2592000   #=> Fri May 09 08:56:03 CDT 2003
  t2 - t             #=> 2592000.0
  t2 - 2592000       #=> Wed Apr 09 08:56:03 CDT 2003

Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:

Time#<=>, Time#<=>===Time#_dump===


 time._dump   => string

Dump time for marshaling.

Time#asctime[править]


 time.asctime => string
 time.ctime   => string

Returns a canonical string representation of time.

  Time.now.asctime   #=> "Wed Apr  9 08:56:03 2003"

Time#ctime[править]


 time.asctime => string
 time.ctime   => string

Returns a canonical string representation of time.

  Time.now.asctime   #=> "Wed Apr  9 08:56:03 2003"

Time#day[править]


 time.day  => fixnum
 time.mday => fixnum

Returns the day of the month (1..n) for time.

  t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
  t.day          #=> 9
  t.mday         #=> 9

Time#dst?[править]


 time.isdst => true or false
 time.dst?  => true or false

Returns true if time occurs during Daylight Saving Time in its time zone.

  Time.local(2000, 7, 1).isdst   #=> true
  Time.local(2000, 1, 1).isdst   #=> false
  Time.local(2000, 7, 1).dst?    #=> true
  Time.local(2000, 1, 1).dst?    #=> false

Time#eql?[править]


 time.eql?(other_time)

Return true if time and other_time are both Time objects with the same seconds and fractional seconds.

Time#getgm[править]


 time.getgm  => new_time
 time.getutc => new_time

Returns a new new_time object representing time in UTC.

  t = Time.local(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000
  t.gmt?                             #=> false
  y = t.getgm                        #=> Sun Jan 02 02:15:01 UTC 2000
  y.gmt?                             #=> true
  t == y                             #=> true

Time#getlocal[править]


 time.getlocal => new_time

Returns a new new_time object representing time in local time (using the local time zone in effect for this process).

  t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
  t.gmt?                          #=> true
  l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
  l.gmt?                          #=> false
  t == l                          #=> true

Time#getutc[править]


 time.getgm  => new_time
 time.getutc => new_time

Returns a new new_time object representing time in UTC.

  t = Time.local(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000
  t.gmt?                             #=> false
  y = t.getgm                        #=> Sun Jan 02 02:15:01 UTC 2000
  y.gmt?                             #=> true
  t == y                             #=> true

Time#gmt?[править]


 time.utc? => true or false
 time.gmt? => true or false

Returns true if time represents a time in UTC (GMT).

  t = Time.now                        #=> Wed Apr 09 08:56:04 CDT 2003
  t.utc?                              #=> false
  t = Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
  t.utc?                              #=> true
  t = Time.now                        #=> Wed Apr 09 08:56:03 CDT 2003
  t.gmt?                              #=> false
  t = Time.gm(2000,1,1,20,15,1)       #=> Sat Jan 01 20:15:01 UTC 2000
  t.gmt?                              #=> true

Time#gmt_offset[править]


 time.gmt_offset => fixnum
 time.gmtoff     => fixnum
 time.utc_offset => fixnum

Returns the offset in seconds between the timezone of time and UTC.

  t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
  t.gmt_offset                    #=> 0
  l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
  l.gmt_offset                    #=> -21600

Time#gmtime[править]


 time.gmtime    => time
 time.utc       => time

Converts time to UTC (GMT), modifying the receiver.

  t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
  t.gmt?         #=> false
  t.gmtime       #=> Wed Apr 09 13:56:03 UTC 2003
  t.gmt?         #=> true
  t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
  t.utc?         #=> false
  t.utc          #=> Wed Apr 09 13:56:04 UTC 2003
  t.utc?         #=> true

Time#gmtoff[править]


 time.gmt_offset => fixnum
 time.gmtoff     => fixnum
 time.utc_offset => fixnum

Returns the offset in seconds between the timezone of time and UTC.

  t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
  t.gmt_offset                    #=> 0
  l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
  l.gmt_offset                    #=> -21600

Time#hash[править]


 time.hash   => fixnum

Return a hash code for this time object.

Time#hour[править]


 time.hour => fixnum

Returns the hour of the day (0..23) for time.

  t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
  t.hour         #=> 8

Time#httpdate[править]


 httpdate()

Returns a string which represents the time as rfc1123-date of HTTP-date defined by RFC 2616:

 day-of-week, DD month-name CCYY hh:mm:ss GMT

Note that the result is always UTC (GMT).

Time#inspect[править]


 time.inspect => string
 time.to_s    => string

Returns a string representing time. Equivalent to calling Time#strftime with a format string of ``%a %b %d %H:%M:%S %Z %Y.

  Time.now.to_s   #=> "Wed Apr 09 08:56:04 CDT 2003"

Time#isdst[править]


 time.isdst => true or false
 time.dst?  => true or false

Returns true if time occurs during Daylight Saving Time in its time zone.

  Time.local(2000, 7, 1).isdst   #=> true
  Time.local(2000, 1, 1).isdst   #=> false
  Time.local(2000, 7, 1).dst?    #=> true
  Time.local(2000, 1, 1).dst?    #=> false

Time#iso8601[править]


 iso8601(fraction_digits=0)

Alias for #xmlschema

Time#localtime[править]


 time.localtime => time

Converts time to local time (using the local time zone in effect for this process) modifying the receiver.

  t = Time.gm(2000, "jan", 1, 20, 15, 1)
  t.gmt?        #=> true
  t.localtime   #=> Sat Jan 01 14:15:01 CST 2000
  t.gmt?        #=> false

Time#marshal_dump[править]


 marshal_dump()

undocumented

Time#marshal_load[править]


 marshal_load(p1)

undocumented

Time#mday[править]


 time.day  => fixnum
 time.mday => fixnum

Returns the day of the month (1..n) for time.

  t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
  t.day          #=> 9
  t.mday         #=> 9

Time#min[править]


 time.min => fixnum

Returns the minute of the hour (0..59) for time.

  t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
  t.min          #=> 56

Time#mon[править]


 time.mon   => fixnum
 time.month => fixnum

Returns the month of the year (1..12) for time.

  t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
  t.mon          #=> 4
  t.month        #=> 4

Time#month[править]


 time.mon   => fixnum
 time.month => fixnum

Returns the month of the year (1..12) for time.

  t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
  t.mon          #=> 4
  t.month        #=> 4

Time#rfc2822[править]


 rfc2822()

Returns a string which represents the time as date-time defined by RFC 2822:

 day-of-week, DD month-name CCYY hh:mm:ss zone

where zone is [+-]hhmm. If self is a UTC time, -0000 is used as zone.

(еще известен как rfc822)

Time#rfc822[править]


 rfc822()

Alias for #rfc2822

Time#sec[править]


 time.sec => fixnum

Returns the second of the minute (0..60)[Yes, seconds really can range from zero to 60. This allows the system to inject leap seconds every now and then to correct for the fact that years are not really a convenient number of hours long.] for time.

  t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
  t.sec          #=> 4

Time#strftime[править]


 Time.strftime( string ) => string

Formats time according to the directives in the given format string. Any text not listed as a directive will be passed through to the output string. Format meaning:

 %a - The abbreviated weekday name (``Sun)
 %A - The  full  weekday  name (``Sunday)
 %b - The abbreviated month name (``Jan)
 %B - The  full  month  name (``January)
 %c - The preferred local date and time representation
 %d - Day of the month (01..31)
 %H - Hour of the day, 24-hour clock (00..23)
 %I - Hour of the day, 12-hour clock (01..12)
 %j - Day of the year (001..366)
 %m - Month of the year (01..12)
 %M - Minute of the hour (00..59)
 %p - Meridian indicator (``AM  or  ``PM)
 %S - Second of the minute (00..60)
 %U - Week  number  of the current year,
         starting with the first Sunday as the first
         day of the first week (00..53)
 %W - Week  number  of the current year,
         starting with the first Monday as the first
         day of the first week (00..53)
 %w - Day of the week (Sunday is 0, 0..6)
 %x - Preferred representation for the date alone, no time
 %X - Preferred representation for the time alone, no date
 %y - Year without a century (00..99)
 %Y - Year with century
 %Z - Time zone name
 %% - Literal ``% character
  t = Time.now
  t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
  t.strftime("at %I:%M%p")            #=> "at 08:56AM"

Time#succ[править]


 time.succ   => new_time

Return a new time object, one second later than time.

Time#to_a[править]


 time.to_a => array

Returns a ten-element array of values for time: {[ sec, min, hour, day, month, year, wday, yday, isdst, zone ]}. See the individual methods for an explanation of the valid ranges of each value. The ten elements can be passed directly to Time::utc or Time::local to create a new Time.

  now = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
  t = now.to_a     #=> [4, 56, 8, 9, 4, 2003, 3, 99, true, "CDT"]

Time#to_f[править]


 time.to_f => float

Returns the value of time as a floating point number of seconds since epoch.

  t = Time.now
  "%10.5f" % t.to_f   #=> "1049896564.13654"
  t.to_i              #=> 1049896564

Time#to_i[править]


 time.to_i   => int
 time.tv_sec => int

Returns the value of time as an integer number of seconds since epoch.

  t = Time.now
  "%10.5f" % t.to_f   #=> "1049896564.17839"
  t.to_i              #=> 1049896564

Time#to_s[править]


 time.inspect => string
 time.to_s    => string

Returns a string representing time. Equivalent to calling Time#strftime with a format string of ``%a %b %d %H:%M:%S %Z %Y.

  Time.now.to_s   #=> "Wed Apr 09 08:56:04 CDT 2003"

Time#to_yaml[править]


 to_yaml( opts = {} )

(нет описания...)

Time#tv_sec[править]


 time.to_i   => int
 time.tv_sec => int

Returns the value of time as an integer number of seconds since epoch.

  t = Time.now
  "%10.5f" % t.to_f   #=> "1049896564.17839"
  t.to_i              #=> 1049896564

Time#tv_usec[править]


 time.usec    => int
 time.tv_usec => int

Returns just the number of microseconds for time.

  t = Time.now        #=> Wed Apr 09 08:56:04 CDT 2003
  "%10.6f" % t.to_f   #=> "1049896564.259970"
  t.usec              #=> 259970

Time#usec[править]


 time.usec    => int
 time.tv_usec => int

Returns just the number of microseconds for time.

  t = Time.now        #=> Wed Apr 09 08:56:04 CDT 2003
  "%10.6f" % t.to_f   #=> "1049896564.259970"
  t.usec              #=> 259970

Time#utc[править]


 time.gmtime    => time
 time.utc       => time

Converts time to UTC (GMT), modifying the receiver.

  t = Time.now   #=> Wed Apr 09 08:56:03 CDT 2003
  t.gmt?         #=> false
  t.gmtime       #=> Wed Apr 09 13:56:03 UTC 2003
  t.gmt?         #=> true
  t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
  t.utc?         #=> false
  t.utc          #=> Wed Apr 09 13:56:04 UTC 2003
  t.utc?         #=> true

Time#utc?[править]


 time.utc? => true or false
 time.gmt? => true or false

Returns true if time represents a time in UTC (GMT).

  t = Time.now                        #=> Wed Apr 09 08:56:04 CDT 2003
  t.utc?                              #=> false
  t = Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
  t.utc?                              #=> true
  t = Time.now                        #=> Wed Apr 09 08:56:03 CDT 2003
  t.gmt?                              #=> false
  t = Time.gm(2000,1,1,20,15,1)       #=> Sat Jan 01 20:15:01 UTC 2000
  t.gmt?                              #=> true

Time#utc_offset[править]


 time.gmt_offset => fixnum
 time.gmtoff     => fixnum
 time.utc_offset => fixnum

Returns the offset in seconds between the timezone of time and UTC.

  t = Time.gm(2000,1,1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
  t.gmt_offset                    #=> 0
  l = t.getlocal                  #=> Sat Jan 01 14:15:01 CST 2000
  l.gmt_offset                    #=> -21600

Time#wday[править]


 time.wday => fixnum

Returns an integer representing the day of the week, 0..6, with Sunday == 0.

  t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
  t.wday         #=> 3

Time#xmlschema[править]


 xmlschema(fraction_digits=0)

Returns a string which represents the time as dateTime defined by XML Schema:

 CCYY-MM-DDThh:mm:ssTZD
 CCYY-MM-DDThh:mm:ss.sssTZD

where TZD is Z or [+-]hh:mm. If self is a UTC time, Z is used as TZD. [+-]hh:mm is used otherwise. fractional_seconds specifies a number of digits of fractional seconds. Its default value is 0.

(еще известен как iso8601)

Time#yday[править]


 time.yday => fixnum

Returns an integer representing the day of the year, 1..366.

  t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
  t.yday         #=> 99

Time#year[править]


 time.year => fixnum

Returns the year for time (including the century).

  t = Time.now   #=> Wed Apr 09 08:56:04 CDT 2003
  t.year         #=> 2003

Time#zone[править]


 time.zone => string

Возвращает наименовние часового поиса. В Ruby 1.8 возвращает UTC , а не GMT для времени UTC.

 t = Time.gm(2000, "jan", 1, 20, 15, 1)
  t.zone   #=> "UTC"
  t = Time.local(2000, "jan", 1, 20, 15, 1)
  t.zone   #=> "CST"

Пример Ruby 2.0

 t=Time.new
  t.zone #=> OMST

Класс TrueClass[править]

Глобальное значение true является единственным экземпляром класса TrueClass и означает логическое «ДА» в алгебре логики. Класс содержит операторы, которые позволяют true корректно вести себя в логических выражениях.


Методы объекта

&, ^, to_s, ||

TrueClass#&[править]


true & obj    #-> true или false

Логическое «И» возвращает false, если objnil или false, true иначе.

TrueClass#^[править]


true ^ obj   #-> !obj

Исключающее «ИЛИ» возвращает true, если objnil или false, false иначе.

TrueClass#to_s[править]


true.to_s   #->  "true"

Всегда возвращает строку "true".

TrueClass#|[править]


true | obj   #-> true

Логического «ИЛИ» всегда возвращает true. obj всегда вычисляется, так как является агрументом метода. В этом случае нет никакого сокращенного вычисления.

true |  puts("или")
true || puts("логическое или")

результат:

или