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)
Методы класса
Методы объекта
[]=, [], &, |, *, +, -, <<, <=>, ==, 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] #=> []
![]() |
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" }
![]() |
Внимание! Для использования методаabbrev необходимо подключение библиотекиabbrev.rb из стандартной библиотеки Руби:require 'abbrev'
|
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]]
![]() |
![]() |
Внимание! Данный метод изменяет исходный массив. Будьте внимательны! Чтобы исключить подобного рода изменения используйте метод + |
Array#at[править]
array.at(index) #=> obj или nil
Возвращает элемент массива array
с индексом index
. Отрицательная индексация подразумевает отсчет с конца массива. возвращаетnil
, если индекс выходит за пределы допустимого диапазона.
a = ["a", "b", "c", "d", "e"]
a.at(0) #=> "a"
a.at(-1) #=> "e"
![]() |
|
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!"]
![]() |
|
![]() |
Внимание! Будьте внимательны при использовании данного итератора, так как он изменяет исходный массив. Чтобы исключить это изменение используйте итераторы collect и map |
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
![]() |
Внимание! Данный метод изменяет исходный массив. Методу compact эта «дурная привычка» не присуща |
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"
![]() |
Внимание! Данный метод изменяет исходный массив. Будьте внимательны! Чтобы исключить подобного рода изменения используйте итератор reject |
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! имеет схожую функциональность |
![]() |
Внимание! Будьте внимательны при использовании данного метода, так как он изменяет исходный массив. Чтобы исключить это изменение используйте метод 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!, которые имеют схожую функциональность |
![]() |
Внимание! Данный итератор изменяет значение исходного массива. Рекомендуется использовать итератор 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]
![]() |
Внимание! Будьте внимательны при использовании данного метода, так как он изменяет исходный массив. Чтобы исключить это изменение используйте метод flatten |
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
![]() |
Внимание! Использование данного метода резко осуждается Руби-сообществом. Во время его использования интерпретатор будет выдавать предупреждение. Рекомендуется использовать метод values_at. |
Array#indices[править]
array.indexes(i1, i2, ... iN) #=> an_array
array.indices(i1, i2, ... iN) #=> an_array
![]() |
Внимание! Использование данного метода резко осуждается Руби-сообществом. Во время его использования интерпретатор будет выдавать предупреждение. Рекомендуется использовать метод values_at. |
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
![]() |
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!"]
![]() |
|
![]() |
Внимание! Будьте внимательны при использовании данного итератора, так как он изменяет исходный массив. Чтобы исключить это изменение используйте итераторы collect и map |
Array#min[править]
array.min #=> obj
Возвращает объект в ary с минимальным значением. Первая форма предполагает, что все объекты реализуют Comparable; вторая использует блок для возврата <=> b.
Array#nitems[править]
![]() |
Внимание! Данный метод удален из Ruby, начиная с версии 1.9. Вместо него можно использовать выражение: array.compact.size |
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
.
Опция | Описание |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
![]() |
Данный метод обычно используется совместно с методом 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]]
![]() |
![]() |
Внимание! Данный метод изменяет исходный массив. Будьте внимательны! Чтобы исключить подобного рода изменения используйте метод + |
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"]
![]() |
|
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, который делает примерно тоже самое, но название которого лучше запоминается |
![]() |
Внимание! Данный метод изменяет исходный массив. Будьте внимательны! Чтобы исключить подобного рода изменения используйте метод [] («батарейка») или итератор reject |
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"]
![]() |
Внимание! Будьте внимательны при использовании данного метода, так как он изменяет исходный массив |
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"]
![]() |
Внимание! Будьте внимательны при использовании данного метода, так как он изменяет исходный массив. Чтобы исключить это изменение используйте метод reverse |
Array#reverse_each[править]
array.reverse_each {|item| block }
Работает точно также, как и итератор each, но элементы массива array
обрабатываются в обратном порядке.
a = ["a", "b", "c"]
a.reverse_each { |x| print x, " " }
результат:
c b a
![]() |
Достичь точно такого же результата можно вот так: |
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, который не только похож по названию, но, в некоторых случаях, работает точно также, как и |
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]
![]() |
Внимание! Данный метод изменяет исходный массив. Будьте внимательны! Чтобы исключить подобного рода изменения используйте метод rotate |
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
![]() |
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) #=> []
![]() |
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 ( |
![]() |
Внимание! Данный метод изменяет исходный массив. Будьте внимательны! Чтобы исключить подобного рода изменения используйте методы [] («батарейка»), values_at или итератор reject |
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 |
![]() |
Внимание! Будьте внимательны при использовании данного итератора, так как он изменяет исходный массив. Чтобы исключить это изменение используйте итераторы sort и 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
![]() |
Внимание! Данный метод изменяет исходный массив. Будьте внимательны! Чтобы исключить подобного рода изменения используйте метод uniq |
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, то есть |
Класс 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, которые имеют схожую функциональность |
![]() |
Внимание! Результат работы данного метода и методов % и 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) |
^ |
| |
+----------------+
Объявленные атрибуты будут доступны в пределах иерархии наследования, где каждый потомок получает копию атрибутов своих родителей, вместо истинного указателя на него. Это означает, что потомок может добавить элементы, для примера, в массив без тех дополнений которые он делит со своим родителем, элементами одного с ним уровня (имеющими общего родителя) или потомками, которые не похожи на правильные атрибуты уровня класса и которые разделены поперек всей иерархии
Методы класса
Методы объекта
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]
Методы объекта
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 корректно вести себя в логических выражениях.
Методы объекта
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)
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
[править]
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
Методы класса
Методы объекта
[], %, &, **, *, +, -@, -, /, <<, <=>, <=, <, ==, >=, >>, >, ^, 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)