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, at, clear, collect!, collect, compact!, compact, concat, 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, nitems, pack, pop, push, rassoc, reject!, reject, replace, reverse!, reverse_each, reverse, rindex, select, shift, 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(size=0, obj=nil) Array.new(array) 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, 6 ] <=> [ 1, 2 ] #=> +1
[править] Array#==
array == other_array -> bool
Равенство — два массива считаются равными, если количество элементов и соответствующие пары элементов равны (используется метод ==).
[ "a", "c" ] == [ "a", "c", 7 ] #=> false
[ "a", "c", 7 ] == [ "a", "c", 7 ] #=> true
[ "a", "c", 7 ] == [ "a", "d", "f" ] #=> 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#[]=
maccuB[uHgekc] = obj -> obj maccuB[cTapT, pa3mep] = obj или an_array или nil -> obj или an_array или nil maccuB[guana3oH] = obj или an_array или nil -> obj или an_array или nil
Распределение элементов — помещает элемент в maccuB по uHgekcу, или заменяет подмассив некоторого pa3mepа, начиная с индекса cTapT, или заменяет подмассив в определенном guana3oHе. Если индексация превышает текущий размер массива, то массив увеличивается автоматически. Отрицательная индексация подразумевает отсчет с конца массива. Если для второго случая использовать pa3mep равный 0, то указанные элементы будут вставлены перед элементом с индексом cTapT. Если все параметры для второго и третьего случая задать равными nil, то из maccuBа будут удалены все элементы. Ошибка 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
maccuB.abbrev(pattern = nil)
Вычисляет набор однозначных сокращений для строк в maccuBe. Если в качестве pattern передается правило или строка, то будут обрабатываться только строки, которые соответствуют правилу или начинаются с данной строки.
%w{ car cone }.abbrev #=> { "ca" => "car", "car" => "car",
"co" => "cone", "con" => cone",
"cone" => "cone" }
[править] Array#assoc
array.assoc(obj) -> an_array или nil
Ищет в двумерном массиве массив, первый элемент которого равен obj (для сравнения используется метод ==). Возвращает первый найденный массив (то есть, ассоциированный массив) или nil, если таковой найти не удалось
s1 = [ "colors", "red", "blue", "green" ]
s2 = [ "letters", "a", "b", "c" ]
s3 = "foo"
a = [ s1, s2, s3 ]
a.assoc("letters") #=> [ "letters", "a", "b", "c" ]
a.assoc("foo") #=> nil
|
Для понимания происходящего, полезно взглянуть на метод rassoc |
[править] Array#at
array.at(index) -> obj или nil
Возвращает элемент массива array с индексом index. Отрицательная индексация подразумевает отсчет с конца массива. возвращает nil, если индекс выходит за пределы допустимого дианазона.
a = [ "a", "b", "c", "d", "e" ]
a.at(0) #=> "a"
a.at(-1) #=> "e"
|
[править] Array#clear
array.clear -> array
Удаляет все элементы из массива array.
a = [ "a", "b", "c", "d", "e" ]
a.clear #=> [ ]
[править] Array#collect
array.collect {|item| block } -> an_array
array.map {|item| block } -> an_array
Выполняет выражение block для каждого элемента массива array. Создает новый массив, который состоит из значений, которые получены при вычислении выражения block.
a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" } #=> ["a!", "b!", "c!", "d!"]
a #=> ["a", "b", "c", "d"]
|
[править] Array#collect!
array.collect! {|item| block } -> array
array.map! {|item| block } -> array
Выполняет выражение block для каждого элемента массива array, вычисленное выражение подставляется вместо текущего элемента.
a = [ "a", "b", "c", "d" ]
a.collect! {|x| x + "!" }
a #=> [ "a!", "b!", "c!", "d!" ]
|
.
[править] Array#compact
array.compact -> an_array
Возвращает копию массива array из которого удалены все элементы nil.
[ "a", nil, "b", nil, "c", nil ].compact
#=> [ "a", "b", "c" ]
[править] Array#compact!
array.compact! -> array или nil
Удаляет все элементы nil из массива array. Возвращает nil, если изменять ничего не потребовалось.
[ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
[ "a", "b", "c" ].compact! #=> nil
[править] Array#concat
array.concat(other_array) -> array
Добавляет к массиву array элементы массива other_array.
[ "a", "b" ].concat( ["c", "d"] ) #=> [ "a", "b", "c", "d" ]
[править] Array#delete
array.delete(obj) -> obj или nil
array.delete(obj){ block } -> obj или nil
Удаляет все элементы массива array, которые равны obj. Если ничего не было удалено, то возвращает nil. Если задан блок, то, в случае отсутствия элементов для удаления, возвращает результат блока.
a = [ "a", "b", "b", "b", "c" ]
a.delete("b") #=> "b"
a #=> ["a", "c"]
a.delete("z") #=> nil
a.delete("z") { "not found" } #=> "not found"
[править] Array#delete_at
array.delete_at(index) -> obj или nil
Удаляет элемент из массива array, который имеет индекс index. Возвращает значение удаленного элемента или nil, если index находится вне допустимого диапазона.
a = %w( ant bat cat dog )
a.delete_at(2) #=> "cat"
a #=> ["ant", "bat", "dog"]
a.delete_at(99) #=> nil
|
Метод slice! имеет схожую функциональность |
[править] Array#delete_if
array.delete_if {|item| block } -> array
Удаляет все элементы массива array для которых значение внутри блока block равно true.
a = [ "a", "b", "c" ]
a.delete_if {|x| x >= "b" } #=> ["a"]
a #=> ["a"]
|
Полезно посмотреть на следующие итераторы reject и reject!, которые имеют схожую функциональность |
[править] Array#each
array.each {|item| block } -> array
Выполняет код в block для каждого элемента массива array, передавая в блок текущий элемент в качестве параметра.
a = [ "a", "b", "c" ]
a.each {|x| print x, " -- " }
результат:
a -- b -- c --
[править] Array#each_index
array.each_index {|index| block } -> array
Работает точно также, как и each, но передает в блок не текущий элемент, а индекс текущего элемента.
a = [ "a", "b", "c" ]
a.each_index {|x| print x, " -- " }
результат:
0 -- 1 -- 2 --
[править] Array#empty?
array.empty? -> true или false
Возвращает true, если array не содержит элементов.
[].empty? #=> true
[править] Array#eql?
array.eql?(other) -> true или false
Возвращает true, если array и other являются одним и тем же объектом или оба массива обладают одинаковым содержимым.
[править] Array#fetch
array.fetch(index) -> obj
array.fetch(index, default ) -> obj
array.fetch(index) {|index| block } -> obj
Попытка получить элемент массива array по индексу index. Если индекс выходит за пределы массива то, в первой форме вызова возникнет ошибка IndexError, во второй форме вызова будет возвращено значение default, и в третьей форме вызова будет возвращено значение блока block (в который передается запрашиваемый индекс в качестве параметра). Отрицательная индексация подразумевает отсчет с конца массива.
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, то это эквивалентно lenght=array.lenght. Последние три формы вызова заполняют массив значением выражения в блоке block (в который передается индекс текущего заменяемого элемента).
a = [ "a", "b", "c", "d" ]
a.fill("x") #=> ["x", "x", "x", "x"]
a.fill("z", 2, 2) #=> ["x", "x", "z", "z"]
a.fill("y", 0..1) #=> ["y", "y", "z", "z"]
a.fill {|i| i*i} #=> [0, 1, 4, 9]
a.fill(-2) {|i| i*i*i} #=> [0, 1, 8, 27]
[править] Array#first
array.first -> obj или nil array.first(n) -> an_array
Возвращает первый элемент или первые n элементов массива array. Если массив пуст, то для первой формы вызова (без n) возвращается nil, а для второй — пустой массив.
a = [ "q", "r", "s", "t" ]
a.first #=> "q"
a.first(1) #=> ["q"]
a.first(3) #=> ["q", "r", "s"]
[править] Array#flatten
array.flatten -> an_array
Преобразует многомерный массив array в одномерный.
s = [ 1, 2, 3 ] #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10
[править] Array#flatten!
array.flatten! -> array или nil
Преобразует многомерный массив array в одномерный. Возвращает nil, если массив array изначально был одномерным.
a = [ 1, 2, [3, [4, 5] ] ]
a.flatten! #=> [1, 2, 3, 4, 5]
a.flatten! #=> nil
a #=> [1, 2, 3, 4, 5]
[править] Array#frozen?
array.frozen? -> true или false
Возвращает true, если массив array заморожен (или временно заморожен, пока идет сортировка).
[править] Array#hash
array.hash -> fixnum
Вычисляет хеш-код для массива array. Два массива с одним и тем же содержимым будут иметь одинаковый хеш-код (именно его использует eql?).
[править] Array#include?
array.include?(obj) -> true или false
Возвращает true, если объект obj является элементом массива array (то есть какой-то из элементов массива == obj). Иначе — false.
a = [ "a", "b", "c" ]
a.include?("b") #=> true
a.include?("z") #=> false
[править] Array#index
array.index(obj) -> int или nil
Возвращает индекс первого вхождения элемента в массив array, который == obj. Возвращает nil, если такой элемент не был найден.
a = [ "a", "b", "c" ]
a.index("b") #=> 1
a.index("z") #=> nil
|
Советую взглянуть на метод rindex, который не только похож по названию, но, в некоторых случаях, работает точно также, как и index |
[править] Array#indexes
array.indexes( i1, i2, ... iN ) -> an_array array.indices( i1, i2, ... iN ) -> an_array
[править] Array#indices
array.indexes( i1, i2, ... iN ) -> an_array array.indices( i1, i2, ... iN ) -> an_array
[править] Array#insert
array.insert(index, obj...) -> array
Вставляет полученные значения перед элементом индексом index (может быть отрицательным).
a = %w{ a b c d }
a.insert(2, 99) #=> ["a", "b", 99, "c", "d"]
a.insert(-2, 1, 2, 3) #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
[править] Array#inspect
array.inspect -> string
Создает «печатную» версию массива array.
[править] 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
Выполняет выражение block для каждого элемента массива array. Создает новый массив, который состоит из значений, которые получены при вычислении выражения block.
a = [ "a", "b", "c", "d" ]
a.map {|x| x + "!" } #=> ["a!", "b!", "c!", "d!"]
a #=> ["a", "b", "c", "d"]
|
[править] Array#map!
array.collect! {|item| block } -> array
array.map! {|item| block } -> array
Выполняет выражение block для каждого элемента массива array, вычисленное выражение подставляется вместо текущего элемента.
a = [ "a", "b", "c", "d" ]
a.map! {|x| x + "!" }
a #=> [ "a!", "b!", "c!", "d!" ]
|
[править] Array#nitems
array.nitems -> int
Возвращает количество элементов массива array, значение которых не равно nil. Может быть нулевым (для пустого массива или массива, который заполнен nil.
[ 1, nil, 3, nil, 5 ].nitems #=> 3
[править] Array#pack
array.pack ( aTemplateString ) -> aBinaryString
Упаковывает содержимое массива array в двоичную последовательность (в виде строки) в соответствии с опциями в строке aTemplateString (см. таблицу ниже). После опций A, a и Z может идти число, которое указывает на ширину результирующего поля. Для остальных, число после опций означает — количество элементов массива которые необходимо обработать в соответствии с указанной опцией. Если в вместо числа после директивы стоит символ * («звездочка»), то все оставшиеся элементы массива необходимо обработать в соответствии с этой опцией. Любую из опций s, S, i, I, l и L можно завершать _ (знаком подчеркивания) для того, чтобы использовать размер для базовой платформы; иначе, будет использован платформонезависимый размер. В строке aTemplateString пробелы игнорируются.
a = [ "a", "b", "c" ]
n = [ 65, 66, 67 ]
a.pack("A3A3A3") #=> "a b c "
a.pack("a3a3a3") #=> "a\000\000b\000\000c\000\000"
n.pack("ccc") #=> "ABC"
Опции метода pack.
| Опция | Описание |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Данный метод обычно используется совместно с методом String#unpack, который выполняет обратные действия |
[править] Array#pop
array.pop -> obj или nil
Удаляет последний элемент из массива array и возвращает его. Если на момент вызова массив был пуст, то возвращает nil.
a = [ "a", "m", "z" ]
a.pop #=> "z"
a #=> ["a", "m"]
[править] 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"]
[править] 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
Возвращает новый массив, состоящий из элементов массива array, для которых значение внутри блока block равно false (или nil).
a = [1,2,3,4,5]
a.reject{ |item| item > 2 } #-> [1,2]
a #-> [1,2,3,4,5]
|
[править] Array#reject!
array.reject! {|item| block } -> array или nil
Подобно итератору delete_if удаляет из массива array элементы, для которых значение внутри блока block равно true, но возвращает nil, если изменений в массиве сделано не было.
a = [1,2,3,4,5]
a.reject!{ |item| item > 2 } #-> [1,2]
a #-> [1,2]
a.reject!{ |item| item > 2 } #-> nil
|
Полезно посмотреть описание итератора delete_if, который делает примерно тоже самое, но название которого лучше запоминается |
[править] Array#replace
array.replace(other_array) -> array
Заменяет содержимое массива 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"]
.
[править] Array#reverse_each
array.reverse_each {|item| block }
Работает точно также, как и итератор each, но элементы массива array обрабатываются в обратном порядке.
a = [ "a", "b", "c" ]
a.reverse_each {|x| print x, " " }
результат:
c b a
|
Достичь точно такого же результата можно вот так: array.reverse.each {|item| block } |
[править] Array#rindex
array.rindex(obj) -> int или nil
Возвращает индекс последнего вхождения элемента в массив array, который == obj. Возвращает nil, если такой элемент не был найден Простым языком - находит obj с конца.
a = [ "a", "b", "b", "b", "c" ]
a.rindex("b") #=> 3
a.rindex("z") #=> nil
|
Советую взглянуть на метод index, который не только похож по названию, но, в некоторых случаях, работает точно также, как и rindex |
[править] Array#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"]
|
Есть итераторы Enumerable#select и #Enumerable#find_all, которые имеют схожую функциональность |
[править] Array#shift
array.shift -> obj or nil
Удаляет первый элемент из массива array и возвращает его (как бы «сдвигает» массив влево на один элемент). Если на момент вызова массив был пуст, то возвращает nil.
args = [ "-m", "-q", "filename" ]
args.shift #=> "-m"
args #=> ["-q", "filename"]
|
Данный метод обычно используют совместно с методами push, pop и unshift |
[править] 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 по индексу (иногда с продолжительностью lenght) или диапазону. Возвращает удаляемые объект, подмассив или nil (если указанный индекс выходит за предел допустимых значений).
def slice!(*args)
result = self[*args]
self[*args] = nil
result
end
a = [ "a", "b", "c" ]
a.slice!(1) #=> "b"
a #=> ["a", "c"]
a.slice!(-1) #=> "c"
a #=> ["a"]
a.slice!(100) #=> nil
a #=> ["a"]
|
Частными реализациями данного метода являются методы pop ( array.slice!(-1) ) и shift ( array.slice!(0) ) |
[править] Array#sort
array.sort -> an_array
array.sort {| a,b | block } -> an_array
Возвращает новый массив, который получен путем сортировки массива array (по возрастанию). Элементы массива должны допускать сравнение при помощи метода <=>, если это не обеспечивается, то можно использовать необязательный блок. Блок предназначенный для сравнения параметров a и b, должен возвращать значения -1, 0, или +1.
a = [ "d", "a", "e", "c", "b" ]
a.sort #=> ["a", "b", "c", "d", "e"]
a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
|
Более интересная и чаще используемая форма сортировки производится при помощи итератора Enumerable#sort_by |
[править] Array#sort!
array.sort! -> array
array.sort! {| a,b | block } -> array
Сортирует массив array (по возрастанию). Элементы массива должны допускать сравнение при помощи метода <=>, если это не обеспечивается, то можно использовать необязательный блок. Блок предназначенный для сравнения параметров a и b, должен возвращать значения -1, 0, или +1.
a = [ "d", "a", "e", "c", "b" ]
a.sort #=> ["a", "b", "c", "d", "e"]
a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
|
Более интересная и чаще используемая форма сортировки производится при помощи метода Enumerable#sort_by |
.
[править] Array#to_a
array.to_a -> array
Возвращает указатель на self. Если вызывается от потомка класса Array, то конвертирует указанный объект в массив (объект класса Array).
[править] Array#to_ary
array.to_ary -> array
Возвращает указатель на self. По сути, ничего не делает.
[править] Array#to_s
array.to_s -> string
Возвращает результат self.join.
[ "a", "e", "i", "o" ].to_s #=> "aeio"
[править] Array#transpose
array.transpose -> an_array
Подразумевает, что array является массивом массивов (то есть с размерностью больше, чем один) и меняет местами столбцы со строками (транспонирует).
a = [[1,2], [3,4], [5,6]]
a.transpose #=> [[1, 3, 5], [2, 4, 6]]
[править] Array#uniq
array.uniq -> an_array
Возвращает новый массив, который получен из массива array путем удаления всех повторяющихся элементов (то есть остаются только «uniq'альные элементы»).
a = [ "a", "a", "b", "b", "c" ]
a.uniq #=> ["a", "b", "c"]
[править] Array#uniq!
array.uniq! -> array или nil
Удаляет из массива array все повторяющиеся элементы (то есть остаются только «uniq'альные элементы»). Возвращает nil, если повторяющиеся элементы в массиве array отсутствовали.
a = [ "a", "a", "b", "b", "c" ]
a.uniq! #=> ["a", "b", "c"]
b = [ "a", "b", "c" ]
b.uniq! #=> nil
[править] Array#unshift
array.unshift(obj, ...) -> array
Добавляет элементы в начало массива array (со сдвигом вправо уже существующих).
a = [ "b", "c", "d" ]
a.unshift("a") #=> ["a", "b", "c", "d"]
a.unshift(1, 2) #=> [ 1, 2, "a", "b", "c", "d"]
a #=> [ 1, 2, "a", "b", "c", "d"]
[править] Array#values_at
array.values_at(selector,... ) -> an_array
Возвращает массив, который состоит из элементов массива array, которые соответствуют передаваемым селекторам. Селекторы могут быть целыми числами (индексами) или целочисленными диапазонами.
a = %w{ a b c d e f }
a.values_at(1, 3, 5)
a.values_at(1, 3, 5, 7)
a.values_at(-1, -3, -5, -7)
a.values_at(1..3, 2...5)
|
Для подобных целей также используются методы select и [] («батарейка»). Вот только в «батарейке» нельзя указывать несколько непоследовательных индексов или диапазонов, а select отбирает элементы по условию (а не по индексу) |
[править] Array#zip
array.zip(arg, ...) -> an_array
array.zip(arg, ...) {| arr | block } -> nil
Преобразует аргументы в массивы (при помощи метода to_a). Объединяет каждый элемент массива array с соответствующим массивом, переданным в качестве аргумента. В результате этого создается двумерный массив с array.size строками и с n столбцами, где n — максимальная из длин аргументов-массивов. Если длина какого либо из аргументов-массивов меньше n, то он расширяется до длины n (дополняется nil). Если задан блок, то получаемые массивы передаются в блок в качестве параметра, иначе — возвращается двумерный массив.
a = [ 4, 5, 6 ]
b = [ 7, 8, 9 ]
[1,2,3].zip(a, b) #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[1,2].zip(a,b) #=> [[1, 4, 7], [2, 5, 8]]
a.zip([1,2],[8]) #=> [[4,1,8], [5,2,nil], [6,nil,nil]]
|
Обычно используется совместно с методом assoc, то есть zip подготавливает для него массив, по которому будет осуществляться ассоциация |
[править] Класс Bignum < Integer
Классу Bignum принадлежат целые числа, которые не умещаются в диапазон класса Fixnum. Объекты класса Bignum создаются автоматически, когда результат вычислений превышает (по модулю) предельное значение класса Fixnum. Когда, в результате вычислений, объект класса Bignum уменьшается настолько, что его значение можно хранить в объекте класса Fixnum, то он автоматически преобразуется в Fixnum. Для обеспечения работы побитовых операций и метода [], объект класса Bignum следует рассматривать как двоичную последовательность бесконечной длины. В отличие от Fixnum, объекты класса Bignum передаются не непосредственно, а по ссылке.
Методы объекта
[], %, &, **, *, +, -@, -, /, <<, <=>, ==, >>, ^, abs, coerce, divmod, div, eql?, hash, modulo, power!, quo, rdiv, remainder, rpower, size, to_f, to_s, ||, ~
[править] Bignum#%
big % other #-> numeric big.modulo(other) #-> numeric
Возвращает остаток от деления числа big на числоother.
1234567890 % 2 #-> 0 1234567890 % 1.2 #-> 4.56881898980299e-008 1234567890 % -2 #-> 0
|
Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации |
|
Методы % и modulo — абсолютно идентичны, то есть являются именами одного и того же метода |
|
Полезно посмотреть на методы **, +, -, / и *, которые имеют схожую функциональность |
[править] Bignum#&
big & numeric #-> integer
Побитовое И.
[править] Bignum#*
big * other #-> numeric
Умножает число big на число other и возвращает результат.
1234567890 * 2 #-> 2469135780 1234567890 * 1.2 #-> 1481481468.0 1234567890 * -2 #-> -2469135780
|
Полезно посмотреть на методы **, +, -, / и %, которые имеют схожую функциональность |
[править] Bignum#**
big ** other #-> numeric big.rpower(other) #-> numeric
Возводит число big в степень other (которая может быть целым, дробным или любым другим числом). Результат может быть класса Fixnum, Bignum или Float.
123456789 ** 2 #-> 15241578750190521 123456789 ** 1.2 #-> 5126464716.09932 123456789 ** -2 #-> 6.5610001194102e-17
|
Полезно посмотреть на методы *, +, -, /, % и power!, которые имеют схожую функциональность |
|
Методы ** и rpower — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Bignum#+
big + other #-> numeric
Складывает число big с числом other и возвращает результат.
1234567890 + 2 #-> 1234567892 1234567890 + 1.2 #-> 1234567891.2 1234567890 + (-2) #-> 1234567888
|
Полезно посмотреть на методы **, *, -, / и %, которые имеют схожую функциональность |
[править] Bignum#-
big - other #-> numeric
Вычитает из числа big число other и возвращает результат.
1234567890 - 2 #-> 1234567888 1234567890 - 1.2 #-> 1234567888.8 1234567890 - (-2) #-> 1234567892
|
Полезно посмотреть на методы **, +, *, / и %, которые имеют схожую функциональность |
[править] Bignum#-@
-big #-> other_big
Унарный минус (возвращает новый объект класса Bignum, значение которого равно 0-big)
[править] Bignum#/
big / other #-> numeric big.div(other) #-> numeric
Делит число big на число other и возвращает результат.
1234567890 / 2 #-> 617283945 1234567890 / 1.2 #-> 1028806575.0 1234567890 / (-2) #-> -617283945
|
Полезно посмотреть на методы **, *, -, +, % и quo, которые имеют схожую функциональность |
|
Методы / и div — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Bignum#<<
big << numeric #-> integer
Побитовый сдвиг числа big влево на numeric позиций (вправо, если numeric меньше нуля).
|
Полезно посмотреть на метод >>, который имеет схожую функциональность |
[править] Bignum#<=>
big <=> numeric #-> -1, 0, +1
Сравнение -- возвращает -1, 0 или +1, если значение числа big меньше, равно или больше значения числа numeric, соотвественно. Это базис для тестов в примеси Comparable.
[править] Bignum#==
big == obj #-> true или false
Возвращает true, если число obj имеет такое же значение, что и число big. В отличие от метода eql?, приводит число obj к классу Bignum.
68719476736 == 68719476736.0 #-> true
[править] Bignum#>>
big >> numeric #-> integer
Побитовый сдвиг числа big вправо на numeric позиций (влево, если numeric меньше нуля).
|
Полезно посмотреть на метод <<, который имеет схожую функциональность |
[править] Bignum#[]
big[n] #-> 0, 1
Побитовый доступ -- возвращает nый бит (виртуальный) двоичного представления числа big, где big[0] -- младший значащий бит.
a = 9**15 50.downto(0) do |n| print a[n] end
результат:
000101110110100000111000011110010100111100010111001
[править] Bignum#^
big ^ numeric #-> integer
Побитовое ИСКЛЮЧАЮЩЕЕ ИЛИ
[править] Bignum#abs
big.abs #-> bignum
Возвращает абсолютное значение числа big.
-1234567890987654321.abs #-> 1234567890987654321
[править] Bignum#coerce
big.coerce(other) #-> array
Возвращает массив, состоящий из чисел other и big, которые преобразованы к классу Bignum.
result = 1234567890.coerce( 1234 ) #-> [1234, 1234567890] result[0] #-> 1234 result[0].class #-> Bignum
[править] Bignum#div
big / other #-> numeric big.div(other) #-> numeric
Делит число big на число other и возвращает результат.
1234567890 / 2 #-> 617283945 1234567890 / 1.2 #-> 1028806575.0 1234567890 / (-2) #-> -617283945
|
Полезно посмотреть на методы **, *, -, +, % и quo, которые имеют схожую функциональность |
|
Методы / и div — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Bignum#divmod
big.divmod(numeric) #-> array
|
Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации |
[править] Bignum#eql?
big.eql?(obj) #-> true или false
Возвращает true, если число obj имеет такое же значение, что и число big. В отличие от метода ==, не занимается приведением типов.
68719476736.eql?(68719476736.0) #-> false
[править] Bignum#hash
big.hash #-> fixnum
Вычисляет контрольную сумму на основе значения числа big.
[править] Bignum#modulo
big % other #-> numeric big.modulo(other) #-> numeric
Возвращает остаток от деления числа big на числоother.
|
Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации |
|
Методы % и modulo — абсолютно идентичны, то есть являются именами одного и того же метода |
|
Полезно посмотреть на методы **, +, -, / и *, которые имеют схожую функциональность |
[править] Bignum#power!
big.power!(other) #-> numeric
Производит возведение числа fix в степень other.
1234567890.power!( 2 ) #-> 1524157875019052100 1234567890.power!( -2 ) #-> 6.5610001194102e-019
|
Полезно посмотреть на методы ** и rpower, которые имеют схожую функциональность |
[править] Bignum#quo
big.quo(other) #-> numeric big.rdiv(other) #-> numeric
Делит число big на число other и в качестве результата возвращает рациональное число.
1234567890.quo(7) #-> Rational(1234567890, 7)
|
Полезно посмотреть на методы / и div, которые имеют схожую функциональность |
|
Методы quo и rdiv — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Bignum#rdiv
big.quo(other) #-> numeric big.rdiv(other) #-> numeric
Делит число big на число other и в качестве результата возвращает рациональное число.
1234567890.rdiv(7) #-> Rational(1234567890, 7)
|
Полезно посмотреть на методы / и div, которые имеют схожую функциональность |
|
Методы quo и rdiv — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Bignum#remainder
big.remainder(numeric) #-> number
Возвращает остаток от деления числа big на число numeric.
-1234567890987654321.remainder(13731) #-> -6966 -1234567890987654321.remainder(13731.24) #-> -9906.22531493148
|
Полезно посмотреть на методы quo, rdiv, % и modulo, которые имеют схожую функциональность |
[править] Bignum#rpower
big ** other #-> numeric big.rpower(other) #-> numeric
Производит возведение числа big в степень other. Возвращает рациональное число, если результат рациональный (то есть, когда other < 0).
1234567890.power!( 2 ) #-> 1524157875019052100 1234567890.power!( -2 ) #-> Rational(1, 1524157875019052100)
|
Методы ** и rpower — абсолютно идентичны, то есть являются именами одного и того же метода |
|
Полезно посмотреть на метод power!, который имеет схожую функциональность |
[править] Bignum#size
big.size #-> integer
Возвращает количество байт машинного представления числа big.
(256**10 - 1).size #-> 12 (256**20 - 1).size #-> 20 (256**40 - 1).size #-> 40
[править] Bignum#to_f
big.to_f #-> float
Преобразует число big в число класса Float. Если число big не может быть преобразовано к классу Float, то возвращает бесконечность.
|
Полезно посмотреть на метод to_s, который имеет схожую функциональность |
[править] Bignum#to_s
big.to_s(base=10) #-> string
Возвращает строку, где число big имеет основание системы счисления равное base (между 2 и 36). По умолчанию base=10 (то есть десятичная система счисления).
12345654321.to_s #-> "12345654321" 12345654321.to_s(2) #-> "1011011111110110111011110000110001" 12345654321.to_s(8) #-> "133766736061" 12345654321.to_s(16) #-> "2dfdbbc31" 78546939656932.to_s(36) #-> "rubyrules"
|
Полезно посмотреть на метод to_f, который имеет схожую функциональность |
[править] Bignum#|
big | numeric #-> integer
Побитовое ИЛИ.
[править] Bignum#~
~big #-> integer
Побитовое НЕ. Так как Bignum теоретически имеет бесконечную длину, то для вычисления результата берется число big на один бит длиннее старшего значащего бита (чтобы операция инверсии была обратимой).
sprintf("%X", ~0x499602d2) #-> "-499602d3" ~~1234567890 #-> 1234567890
[править] Класс Class < Module
Классы в Руби это уникальные объекты --- каждый из которых является экземпляром класса Class. Когда новый класс создается (обычно используется class Name ... end), объект типа Class создается и присваивается одноименной глобальной переменной (в данном случае Name). Когда вызывается Name.new для создания нового объекта, запускается метод new класса Class. Это можно продемонстрировать перегрузкой метода new в классе Class:
class Class alias oldNew new def new(*args) print "Создается новый ", self.name, "\n" oldNew(*args) end end class Name end n = Name.new
результат:
Создается новый Name
Классы, модули и объекты взаимосвязаны. На следующей диаграмме, вертикальными стрелками обозначено наследование, а круглыми скобками --- метаклассы. Все метаклассы это объекты класса `Class'.
+------------------+
| |
Object---->(Object) |
^ ^ ^ ^ |
| | | | |
| | +-----+ +---------+ |
| | | | |
| +-----------+ | |
| | | | |
+------+ | Module--->(Module) |
| | ^ ^ |
OtherClass-->(OtherClass) | | |
| | |
Class---->(Class) |
^ |
| |
+----------------+
Объявленные атрибуты будут доступны в пределах иерархии наследования, где каждый потомок получает копию атрибутов своих родителей, вместо истинного указателя на него. Это означает, что потомок может добавить элементы, для примера, в массив без тех дополнений которые он делит со своим родителем, элементами одного с ним уровня (имеющими общего родителя) или потомками, которые не похожи на правильные атрибуты уровня класса и которые разделены поперек всей иерархии
Методы класса
Методы объекта
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
Equivalent to calling dir.glob(string,0).
[править] Dir::chdir
Dir.chdir( [ string] ) => 0
Dir.chdir( [ string] ) {| path | block } => anObject
Changes the current working directory of the process to the given string. When called without an argument, changes the directory to the value of the environment variable HOME, or LOGDIR. SystemCallError (probably Errno::ENOENT) if the target directory does not exist. If a block is given, it is passed the name of the new current directory, and the block is executed with that as the current directory. The original working directory is restored when the block exits. The return value of chdir is the value of the block. chdir blocks can be nested, but in a multi-threaded program an error will be raised if a thread attempts to open a chdir block while another thread has one open.
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
produces:
/var/spool/mail
/tmp
/usr
/tmp
/var/spool/mail
[править] Dir::chroot
Dir.chroot( string ) => 0
Changes this process's idea of the file system root. Only a privileged process may make this call. Not available on all platforms. On Unix systems, see chroot(2) for more information.
[править] Dir::create_junction
Dir::create_junction(to, from)
Creates the symlink to, linked to the existing directory from. If the to directory already exists, it must be empty or an error is raised.
[править] Dir::delete
Dir.delete( string ) => 0 Dir.rmdir( string ) => 0 Dir.unlink( string ) => 0
Deletes the named directory. Raises a subclass of SystemCallError if the directory isn't empty.
[править] Dir::empty?
Dir::empty?(path)
Returns whether or not path is empty. Returns false if path is not a directory, or contains any files other than '.' or '..'.
[править] Dir::entries
Dir.entries( dirname ) => array
Returns an array containing all of the filenames in the given directory. Will raise a SystemCallError if the named directory doesn't exist.
Dir.entries("testdir") #=> [".", "..", "config.h", "main.rb"]
[править] Dir::foreach
Dir.foreach( dirname ) {| filename | block } => nil
Calls the block once for each entry in the named directory, passing the filename of each entry as a parameter to the block.
Dir.foreach("testdir") {|x| puts "Got #{x}" }
produces:
Got .
Got ..
Got config.h
Got main.rb
[править] Dir::getwd
Dir.getwd => string Dir.pwd => string
Returns the path to the current working directory of this process as a string.
Dir.chdir("/tmp") #=> 0
Dir.getwd #=> "/tmp"
[править] Dir::glob
Dir.glob( string, [flags] ) => array
Dir.glob( string, [flags] ) {| filename | block } => nil
Returns the filenames found by expanding the pattern given in string, either as an array or as parameters to the block. Note that this pattern is not a regexp (it's closer to a shell glob). See File::fnmatch for the meaning of the flags parameter.
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 directories recursively. 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]). Matches either literal p or literal q. Matching literals may be more than one character in length. More than two literals may be specified. Equivalent to pattern alternation in regexp.
Escapes the next metacharacter.
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)
Returns whether or not path is a junction.
[править] Dir::mkdir
Dir.mkdir( string [, integer] ) => 0
Makes a new directory named by string, with permissions specified by the optional parameter anInteger. The permissions may be modified by the value of File::umask, and are ignored on NT. Raises a SystemCallError if the directory cannot be created. See also the discussion of permissions in the class documentation for File.
[править] Dir::new
Dir.new( string ) -> aDir
Returns a new directory object for the named directory.
[править] Dir::open
Dir.open( string ) => aDir
Dir.open( string ) {| aDir | block } => anObject
With no block, open is a synonym for Dir::new. If a block is present, it is passed aDir as a parameter. The directory is closed at the end of the block, and Dir::open returns the value of the block.
[править] Dir::pwd
Dir.getwd => string Dir.pwd => string
Returns the path to the current working directory of this process as a string.
Dir.chdir("/tmp") #=> 0
Dir.getwd #=> "/tmp"
[править] Dir::rmdir
Dir.delete( string ) => 0 Dir.rmdir( string ) => 0 Dir.unlink( string ) => 0
Deletes the named directory. Raises a subclass of SystemCallError if the directory isn't empty.
[править] Dir::tmpdir
Dir::tmpdir()
Returns the operating system's temporary file path.
[править] Dir::unlink
Dir.delete( string ) => 0 Dir.rmdir( string ) => 0 Dir.unlink( string ) => 0
Deletes the named directory. Raises a subclass of SystemCallError if the directory isn't empty.
[править] Dir#close
dir.close => nil
Closes the directory stream. Any further attempts to access dir will raise an IOError.
d = Dir.new("testdir")
d.close #=> nil
[править] Dir#each
dir.each { |filename| block } => dir
Calls the block once for each entry in this directory, passing the filename of each entry as a parameter to the block.
d = Dir.new("testdir")
d.each {|x| puts "Got #{x}" }
produces:
Got .
Got ..
Got config.h
Got main.rb
[править] Dir#path
dir.path => string or nil
Returns the path parameter passed to dir's constructor.
d = Dir.new("..")
d.path #=> ".."
[править] Dir#pos
dir.pos => integer dir.tell => integer
Returns the current position in dir. See also Dir#seek.
d = Dir.new("testdir")
d.tell #=> 0
d.read #=> "."
d.tell #=> 12
[править] Dir#pos=
dir.pos( integer ) => integer
Synonym for Dir#seek, but returns the position parameter.
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
Reads the next entry from dir and returns it as a string. Returns nil at the end of the stream.
d = Dir.new("testdir")
d.read #=> "."
d.read #=> ".."
d.read #=> "config.h"
[править] Dir#rewind
dir.rewind => dir
Repositions dir to the first entry.
d = Dir.new("testdir")
d.read #=> "."
d.rewind #=> #<Dir:0x401b3fb0>
d.read #=> "."
[править] Dir#seek
dir.seek( integer ) => dir
Seeks to a particular location in dir. integer must be a value returned by 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
Returns the current position in dir. See also Dir#seek.
d = Dir.new("testdir")
d.tell #=> 0
d.read #=> "."
d.tell #=> 12
[править] Примесь Enumerable
The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection. If Enumerable#max, #min, or #sort is used, the objects in the collection must also implement a meaningful <=> operator, as these methods rely on an ordering between members of the collection.
Методы объекта
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
Passes each element of the collection to the given block. The method returns true if the block never returns false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is all? will return true only if none of the collection members are false or 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
Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or 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
Returns a new array with the results of running block once for every element in 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
Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns 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) {...}
Iterates the given block for each array of consecutive <n> elements. e.g.:
(1..10).each_cons(3) {|a| p a}
# outputs below
[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) {...}
Iterates the given block for each slice of <n> elements. e.g.:
(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
Calls block with two arguments, the item and its index, for each item in enum.
hash = Hash.new
%w(cat dog wombat).each_with_index {|item, index|
hash[item] = index
}
hash #=> {"cat"=>0, "wombat"=>2, "dog"=>1}
[править] Enumerable#entries
enum.to_a => array enum.entries => array
Returns an array containing the items in 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)
Returns Enumerable::Enumerator.new(self, :each_cons, n).
[править] Enumerable#enum_slice
e.enum_slice(n)
Returns Enumerable::Enumerator.new(self, :each_slice, n).
[править] Enumerable#enum_with_index
enum_with_index
Returns 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
Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns 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
Returns an array containing all elements of enum for which block is not false (see also 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
Returns an array of every element in enum for which Pattern === element. If the optional block is supplied, each matching element is passed to it, and the block's result is stored in the output array.
(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| ...}
Collect an enumerable into sets, grouped by the result of a block. Useful, for example, for grouping records by date. e.g.
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
Returns true if any member of enum equals obj. Equality is tested using ==.
IO.constants.include? "SEEK_SET" #=> true
IO.constants.include? "SEEK_NO_FURTHER" #=> false
[править] Enumerable#index_by
index_by() {|elem| ...}
Convert an enumerable to a hash. Examples:
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
Combines the elements of enum by applying the block to an accumulator value (memo) and each element in turn. At each step, memo is set to the value returned by the block. The first form lets you supply an initial value for memo. The second form uses the first element of the collection as a the initial value (and skips that element while iterating).
# Sum some numbers
(5..10).inject {|sum, n| sum + n } #=> 45
# Multiply some numbers
(5..10).inject(1) {|product, n| product * n } #=> 151200
# find the longest word
longest = %w{ cat sheep bear }.inject do |memo,word|
memo.length > word.length ? memo : word
end
longest #=> "sheep"
# find the length of the longest word
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
Returns a new array with the results of running block once for every element in 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
Returns the object in enum with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return 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 or false enum.member?(obj) => true or false
Returns true if any member of enum equals obj. Equality is tested using ==.
IO.constants.include? "SEEK_SET" #=> true
IO.constants.include? "SEEK_NO_FURTHER" #=> false
[править] Enumerable#min
enum.min => obj
enum.min {| a,b | block } => obj
Returns the object in enum with the minimum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.
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 ]
Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.
(1..6).partition {|i| (i&1).zero?} #=> [[2, 4, 6], [1, 3, 5]]
[править] Enumerable#reject
enum.reject {| obj | block } => array
Returns an array for all elements of enum for which block is false (see also 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
Returns an array containing all elements of enum for which block is not false (see also Enumerable#reject).
(1..10).find_all {|i| i % 3 == 0 } #=> [3, 6, 9]
[править] Enumerable#sort
enum.sort => array
enum.sort {| a, b | block } => array
Returns an array containing the items in enum sorted, either according to their own <=> method, or by using the results of the supplied block. The block should return -1, 0, or +1 depending on the comparison between a and b. As of Ruby 1.8, the method Enumerable#sort_by implements a built-in Schwartzian Transform, useful when key computation or comparison is expensive..
%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
Sorts enum using a set of keys generated by mapping the values in enum through the given block.
%w{ apple pear fig }.sort_by {|word| word.length}
#=> ["fig", "pear", "apple"]
The current implementation of sort_by generates an array of tuples containing the original collection element and the mapped value. This makes sort_by fairly expensive when the keysets are simple
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
produces:
user system total real
Sort 0.180000 0.000000 0.180000 ( 0.175469)
Sort by 1.980000 0.040000 2.020000 ( 2.013586)
However, consider the case where comparing the keys is a non-trivial operation. The following code sorts some files on modification time using the basic sort method.
files = Dir["*"]
sorted = files.sort {|a,b| File.new(a).mtime <=> File.new(b).mtime}
sorted #=> ["mon", "tues", "wed", "thurs"]
This sort is inefficient: it generates two new File objects during every comparison. A slightly better technique is to use the Kernel#test method to generate the modification times directly.
files = Dir["*"]
sorted = files.sort { |a,b|
test(?M, a) <=> test(?M, b)
}
sorted #=> ["mon", "tues", "wed", "thurs"]
This still generates many unnecessary Time objects. A more efficient technique is to cache the sort keys (modification times in this case) before the sort. Perl users often call this approach a Schwartzian Transform, after Randal Schwartz. We construct a temporary array, where each element is an array containing our sort key along with the filename. We sort this array, and then extract the filename from the result.
sorted = Dir["*"].collect { |f|
[test(?M, f), f]
}.sort.collect { |f| f[1] }
sorted #=> ["mon", "tues", "wed", "thurs"]
This is exactly what sort_by does internally.
sorted = Dir["*"].sort_by {|f| test(?M, f)}
sorted #=> ["mon", "tues", "wed", "thurs"]
[править] Enumerable#sum
sum(identity = 0, &block)
Calculates a sum from the elements. Examples:
payments.sum { |p| p.price * p.tax_rate }
payments.sum(&:price)
This is instead of payments.inject { |sum, p| sum + p.price } Also calculates sums without the use of a block:
[5, 15, 10].sum # => 30
The default identity (sum of an empty list) is zero. However, you can override this default: [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
[править] Enumerable#to_a
enum.to_a => array enum.entries => array
Returns an array containing the items in 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)
Makes a set from the enumerable object with given arguments. Needs to +require "set"+ to use this method.
[править] Enumerable#zip
enum.zip(arg, ...) => array
enum.zip(arg, ...) {|arr| block } => nil
Converts any arguments to arrays, then merges elements of enum with corresponding elements from each argument. This generates a sequence of enum#size n-element arrays, where n is one more that the count of arguments. If the size of any argument is less than enum#size, nil values are supplied. If a block given, it is invoked for each output array, otherwise an array of arrays is returned.
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)
Returns true if the file or directory is an archive file. Applications use this attribute to mark files for backup or removal.
[править] File::atime
File.atime(file_name) => time
Returns the last access time for the named file as a Time object).
File.atime("testfile") #=> Wed Apr 09 08:51:48 CDT 2003
[править] File::attributes
File::attributes(file)
Returns an array of strings indicating the attributes for that file. The possible values are: archive compressed directory encrypted hidden indexed normal offline readonly reparse_point sparse system temporary Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:
File::basename, File::basename===File::blksize===
File::blksize(file)
Returns the file system's block size. Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:
File::blockdev?, 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::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 exists.
[править] File::exists?
File.exist?(file_name) => true or false File.exists?(file_name) => true or false (obsolete)
Return true if the named file exists.
[править] 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)
|
Методы ** и rpower — абсолютно идентичны, то есть являются именами одного и того же метода |
|
Полезно посмотреть на методы *, +, -, /, % и power!, которые имеют схожую функциональность |
[править] Fixnum#+
fix + numeric #-> numeric_result
Производит сложение: результат является одним из потомков класса Numeric и зависит от величины результата.
|
Полезно посмотреть на методы **, *, -, / и %, которые имеют схожую функциональность |
[править] Fixnum#-
fix - numeric #-> numeric_result
Производит вычитание: результат является одним из потомков класса Numeric и зависит от величины результата.
|
Полезно посмотреть на методы **, +, *, / и %, которые имеют схожую функциональность |
[править] Fixnum#-@
-fix #-> integer
Отрицание fix (может вернуть значение класса Bignum).
[править] Fixnum#/
fix / numeric #-> numeric_result fix.div(numeric) #-> numeric_result
Производит целочисленное деление: результат является одним из потомков класса Numeric и зависит от величины результата.
|
Методы / и div — абсолютно идентичны, то есть являются именами одного и того же метода |
|
Полезно посмотреть на методы **, +, -, * и %, которые имеют схожую функциональность |
[править] Fixnum#<
fix < other #-> true или false
Возвращает true, если значение числа fix меньше, чем значение числа other.
[править] Fixnum#<<
fix << count #-> integer
Побитовый сдвиг числа fix влево на count позиций (вправо, если count меньше нуля).
[править] Fixnum#<=
fix <= other #-> true или false
Возвращает true, если значение числа fix меньше или равно значению числа other.
[править] Fixnum#<=>
fix <=> numeric #-> -1, 0, +1
Сравнение -- возвращает -1, 0 или +1, если значение числа fix меньше, равно или больше значения числа numeric, соотвественно. Это базис для тестов в примеси Comparable.
[править] Fixnum#==
fix == other #-> true или false
Возвращает true, если значение числа fix равно значениею числа other.
1 == 2 #-> false 1 == 1.0 #-> true
[править] Fixnum#>
fix > other #-> true или false
Возвращает true, если значение числа fix больше, чем значение числа other.
[править] Fixnum#>=
fix >= other #-> true или false
Возвращает true, если значение числа fix больше или равно, чем значение числа other.
[править] Fixnum#>>
fix >> count #-> integer
Побитовый сдвиг числа fix вправо на count позиций (влево, если count меньше нуля).
[править] Fixnum#[]
fix[n] #-> 0, 1
Побитовый доступ -- возвращает nый бит двоичного представления числа fix, где fix[0] -- младший significant бит.
a = 0b11001100101010 30.downto(0) do |n| print a[n] end
результат:
0000000000000000011001100101010
[править] Fixnum#^
fix ^ other #-> integer
Побитовое ИСКЛЮЧАЮЩЕЕ ИЛИ.
[править] Fixnum#abs
fix.abs #-> fixnum
Возвращает абсолютное значение числа fix.
-12345.abs #-> 12345 12345.abs #-> 12345
[править] Fixnum#div
fix / numeric #-> numeric_result fix.div(numeric) #-> numeric_result
Производит целочисленное деление: результат является одним из потомков класса Numeric и зависит от величины результата.
|
Методы / и div — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Fixnum#divmod
fix.divmod(numeric) #-> array
|
Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации |
[править] Fixnum#id2name
fix.id2name #-> string или nil
Возвращает имя объекта с id равным fix. Возвращает nil, если в символьной таблице не найдено ни одного символа, соответствующего значению fix.
symbol = :@inst_var #-> :@inst_var id = symbol.to_i #-> 9818 id.id2name #-> "@inst_var"
|
[править] Fixnum#modulo
fix % other #-> Numeric fix.modulo(other) #-> Numeric
Возвращает остаток от деления числа fix на числоother.
|
Полезно взглянуть в описание метода Numeric#divmod для получения более детальной информации |
|
Методы % и modulo — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Fixnum#power!
fix.power!( other ) #-> numeric
Производит возведение числа fix в степень other.
2.power!( 8 ) #-> 256 2.power( -8 ) #-> 0.00390625
|
Полезно посмотреть на методы ** и rpower, которые имеют схожую функциональность |
[править] Fixnum#quo
fix.quo(numeric) #-> float fix.rdiv(numeric) #-> float
Возвращает дробный результат деления числа fix на число numeric.
654321.quo(13731) #-> 47.6528293642124 654321.quo(13731.24) #-> 47.6519964693647
|
Методы quo и rdiv — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Fixnum#rdiv
fix.quo(numeric) #-> float fix.rdiv(numeric) #-> float
Возвращает дробный результат деления числа fix на число numeric.
654321.rdiv(13731) #-> 47.6528293642124 654321.rdiv(13731.24) #-> 47.6519964693647
|
Методы quo и rdiv — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Fixnum#rpower
fix ** other #-> rational или numeric fix.rpower(other) #-> rational или numeric
Производит возведение числа fix в степень other. Возвращает рациональное число, если результат рациональный (то есть, когда other < 0).
2.rpower( 8 ) #-> 256 2.rpower( -8 ) #-> Rational(1,256)
|
Методы ** и rpower — абсолютно идентичны, то есть являются именами одного и того же метода |
|
Полезно посмотреть на метод power!, который имеет схожую функциональность |
[править] Fixnum#size
fix.size #-> fixnum
Возвращает количество байт машинного представления числа fix.
1.size #-> 4 -1.size #-> 4 2147483647.size #-> 4
[править] Fixnum#to_f
fix.to_f #-> float
Преобразует значение числа fix к классу Float.
|
Полезно посмотреть на методы to_s и to_sym, которые имеют схожую функциональность |
[править] Fixnum#to_s
fix.to_s( base=10 ) #-> string
Возвращает строку, где число fix имеет основание системы счисления равное base (между 2 и 36). По умолчанию base=10 (то есть десятичная система счисления).
12345.to_s #-> "12345" 12345.to_s(2) #-> "11000000111001" 12345.to_s(8) #-> "30071" 12345.to_s(10) #-> "12345" 12345.to_s(16) #-> "3039" 12345.to_s(36) #-> "9ix"
|
Полезно посмотреть на методы to_f и to_sym, которые имеют схожую функциональность |
[править] Fixnum#to_sym
fix.to_sym #-> symbol
Возвращает символ, которому соотвествует значение fix.
fred = :fred.to_i fred.id2name #-> "fred" fred.to_sym #-> :fred
|
Полезно посмотреть на методы to_s, to_f и id2name, которые имеют схожую функциональность |
[править] Fixnum#zero?
fix.zero? #-> true или false
Возвращает true, если значение fix равно нулю.
[править] Fixnum#|
fix | other #-> integer
Побитовое ИЛИ.
[править] Fixnum#~
~fix #-> integer
Побитовое НЕ.
[править] Класс Float < Numeric
Объекты класса Float представляют собой вещественные числа, то есть дробные числа с плавающей точкой двойной точности (аналог типа double в языке Си).
Примеси
Precision (prec, prec_f, prec_i)
Константы
DIG, EPSILON, MANT_DIG, MAX, MAX_10_EXP, MAX_EXP, MIN, MIN_10_EXP, MIN_EXP, RADIX, ROUNDS
Методы класса
Методы объекта
%, **, *, +, -@, -, /, <->, <=, <, ==, >=, >, abs, ceil, coerce, divmod, eql?, finite?, floor, hash, infinite?, modulo, nan?, round, to_f, to_int, to_i, to_s, truncate, zero?
[править] Float::induced_from
Float.induced_from(obj) #-> float
Преобразует obj в вещественное число.
[править] Float#%
flt % other #-> float flt.modulo(other) #-> float
Возвращает остаток от деления числа flt на число other.
6543.21 % 137 #-> 104.21 6543.21 % 137.24 #-> 92.9299999999996
|
Методы % и modulo — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Float#*
flt * other #-> float
Возвращает вещественное число, которое является результатом произведения flt на other.
|
Полезно посмотреть на методы **, +, -, / и %, которые имеют схожую функциональность |
[править] Float#**
flt ** other #-> float
Возвращает вещественное число, которое является результатом возведения числа flt в степень other.
|
Полезно посмотреть на методы *, +, -, / и %, которые имеют схожую функциональность |
[править] Float#+
flt + other #-> float
Возвращает вещественное число, которое является суммой чисел flt и other.
|
Полезно посмотреть на методы **, *, -, / и %, которые имеют схожую функциональность |
[править] Float#-
flt - other #-> float
Возвращает вещественное число, которое является разностью чисел flt и other.
|
Полезно посмотреть на методы **, +, *, / и %, которые имеют схожую функциональность |
[править] Float#-@
-flt #-> float
Возвращает вещественное число, обратное по знаку (по отношению к flt).
[править] Float#/
float / other #-> float
Возвращает вещественное число, которое является частным чисел flt и other.
|
Полезно посмотреть на методы **, +, -, * и %, которые имеют схожую функциональность |
[править] Float#<
flt < other #-> true или false
Возвращает true, если число flt меньше, чем число other.
[править] Float#<=
flt <= other #-> true or false
Возвращает true, если число flt меньше или равно по отношению к числу other.
[править] Float#<=>
flt <=> numeric #-> -1, 0, +1
Возвращает -1, 0 или +1, когда число flt меньше, равно или больше числа numeric, соотвественно. Этот метод необходим для нормальной работы примеси Comparable.
[править] Float#==
flt == obj #-> true или false
Возвращает true только если число obj имеет точно такое же значение, как и число flt. В отличие от метода eql?, преобразует obj в вещественное число.
1.0 == 1 #-> true
[править] Float#>
flt > other #-> true или false
Возвращает true, если число flt больше, чем число other.
[править] Float#>=
flt >= other #-> true или false
Возвращает true, если число flt больше или равно по отношению к числу other.
[править] Float#abs
flt.abs #-> float
Возвращает абсолютную величину числа flt.
(-34.56).abs #-> 34.56 -34.56.abs #-> 34.56
[править] Float#ceil
flt.ceil #-> integer
Возвращает наименьшее целое число большее или равное числу flt.
1.2.ceil #-> 2 2.0.ceil #-> 2 (-1.2).ceil #-> -1 (-2.0).ceil #-> -2
|
Полезно посмотреть на методы floor, round и truncate, которые имеют схожую функциональность |
[править] Float#coerce
flt.coerce(other) #-> array
Возвращает массив, состоящий из чисел other и flt, которые преобразованы к вещественному типу. Этот метод используется при обработке арифметических операций со смешанными типами.
1.2.coerce(3) #-> [3.0, 1.2] 1.0.coerce(2.0) #-> [2.0, 1.0]
[править] Float#divmod
flt.divmod(numeric) #-> array
См. описание метода Numeric#divmod.
[править] Float#eql?
flt.eql?(obj) #-> true или false
Возвращает true, если obj является вещественным числом и имеет значение равное flt. В отличие от метода ==, преобразований типов не производится.
1.0.eql?(1) #-> false
[править] Float#finite?
flt.finite? #-> true или false
Возвращает true, если flt является правильным вещественным числом по стандартам IEEE (то есть не является бесконечностью и метод nan? возвращает false).
[править] Float#floor
flt.floor #-> integer
Возвращает наибольшее целое, меньшее или равное flt.
1.2.floor #-> 1 2.0.floor #-> 2 (-1.2).floor #-> -2 (-2.0).floor #-> -2
|
Полезно посмотреть на методы ceil, round и truncate, которые имеют схожую функциональность |
[править] Float#hash
flt.hash #-> integer
Возвращает хеш-код вещественного числа flt.
[править] Float#infinite?
flt.infinite? #-> nil, -1, +1
Возвращает nil, -1 или +1, если вещественное число flt конечно, устремлено в
или в
, соотвественно.
(0.0).infinite? #-> nil (-1.0/0.0).infinite? #-> -1 (+1.0/0.0).infinite? #-> 1
[править] Float#modulo
flt % other #-> float flt.modulo(other) #-> float
Возвращает остаток от деления числа flt на число other.
6543.21.modulo(137) #-> 104.21 6543.21.modulo(137.24) #-> 92.9299999999996
[править] Float#nan?
flt.nan? -> true или false
Возвращает true, если число flt не удовлетворяет стандарту IEEE на вещественные числа.
a = -1.0 #-> -1.0 a.nan? #-> false a = 0.0/0.0 #-> NaN a.nan? #-> true
[править] Float#round
flt.round #-> integer
Возвращает ближайшее целое число к вещественному числу flt. Метод эквивалентен следующей записи:
def round return floor(self+0.5) if self > 0.0 return ceil(self-0.5) if self < 0.0 return 0.0 end 1.5.round #-> 2 (-1.5).round #-> -2
|
Полезно посмотреть на методы floor, ceil и truncate, которые имеют схожую функциональность |
[править] Float#to_f
flt.to_f #-> flt
Так как ftl уже является вещественным числом, то данный метод всегда возвращает ftl.
[править] Float#to_i
flt.to_i #-> integer flt.to_int #-> integer flt.truncate #-> integer
Возвращает целое число, которое является целой частью вещественного числа flt.
|
Методы to_i, to_int и truncate — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Float#to_int
flt.to_i #-> integer flt.to_int #-> integer flt.truncate #-> integer
Возвращает целое число, которое является целой частью вещественного числа flt.
|
Методы to_i, to_int и truncate — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Float#to_s
flt.to_s #-> string
Возвращает строку, которая содержит строковое представление вещественного числа flt. Число flt может быть представлено как в обычной, так и в экспоненциальной форме записи, а также иметь значения NaN, Infinity, -Infinity.
[править] Float#truncate
flt.to_i #-> integer flt.to_int #-> integer flt.truncate #-> integer
Возвращает целое число, которое является целой частью вещественного числа flt.
|
Полезно посмотреть на методы floor, round и ceil, которые имеют схожую функциональность |
|
Методы to_i, to_int и truncate — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Float#zero?
flt.zero? -> true или false
Возвращает true, если вещественное число flt является числом 0.0.
[править] Класс GC
Модуль GC обеспечивает Руби-интерфейс, который позволяет управлять механизмом сборки мусора. Некоторые из методов также доступны через модуль ObjectSpace.
Методы класса
Методы объекта
[править] GC::disable
GC.disable #-> true или false
Отключает сборку мусора, возвращает true если сборка мусора уже была отключена.
GC.disable #-> false GC.disable #-> true
[править] GC::enable
GC.enable #-> true или false
Включает сборку мусора, возвращает true если сборка мусора была предварительно отключена.
GC.disable #-> false GC.enable #-> true GC.enable #-> false
[править] GC::start
GC.start #-> nil gc.garbage_collect #-> nil ObjectSpace.garbage_collect #-> nil
Начинает сборку мусора, пока не отключена вручную.
[править] GC#garbage_collect
GC.start #-> nil gc.garbage_collect #-> nil ObjectSpace.garbage_collect #-> nil
Начинает сборку мусора, пока не отключена вручную.
[править] Класс Hash
Хеш - коллекция пар ключ-значение. Хеш подобен классу Array, за исключением того, что индексация осуществляется через ключи (объекты любого типа), а не через целочисленные индексы. Последовательность перечисления пар ключ-значений хеша может оказаться произвольной, и обычно не совпадает с той, в которой вы заполняли хеш. При обращении к хешу по ключу, которого не существует, возвращается значение по-умолчанию. Изначально, этим значением является nil.
Примеси
Enumerable (all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find, find_all, grep, group_by, include?, index_by, inject, map, max, member?, min, partition, reject, select, sort, sort_by, sum, to_a, to_set, zip)
Методы класса
Методы объекта
[]=, [], ==, clear, default=, default_proc, default, delete_if, delete, each_key, each_pair, each_value, each, empty?, fetch, has_key?, has_value?, include?, indexes, index, indices, inspect, invert, key?, keys, length, member?, merge!, merge, rehash, reject!, reject, replace, select, shift, size, sort, store, to_a, to_hash, to_s, update, value?, values_at, values
[править] Hash::[]
Hash[ [key =>|, value]* ] #-> hash
Создает новый хеш, заполненный заданными объектами. Эквивалентно литералу { key, value, ... }.
Hash["a", 100, "b", 200] #-> {"a"=>100, "b"=>200} Hash["a" => 100, "b" => 200] #-> {"a"=>100, "b"=>200} { "a" => 100, "b" => 200 } #-> {"a"=>100, "b"=>200}
[править] Hash::new
Hash.new #-> hash Hash.new(obj) #-> aHash Hash.new {|hash, key| block } #-> aHash
Возвращает новый хеш. При последующем обращении к хешу по ключу, которого не существует в этом хеше, возвращаемое значение зависит от формы вызова метода new. В первой форме вызова вернется значение nil. Если указан объект obj, то этот единственный объект будет использоваться для всех значений по-умолчанию. Если указан блок, тогда значение по-умолчанию вычисляется в данном блоке, которому передаются хеш (текущий) и ключ. В блоке можно записать значение в хеш, если это необходимо.
h = Hash.new("Go Fish") h["a"] = 100 h["b"] = 200 h["a"] #-> 100 h["c"] #-> "Go Fish" # Изменяется единственный объект по-умолчанию h["c"].upcase! #-> "GO FISH" h["d"] #-> "GO FISH" h.keys #-> ["a", "b"] # Создается новый объект по умолчанию каждый раз h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" } h["c"] #-> "Go Fish: c" h["c"].upcase! #-> "GO FISH: C" h["d"] #-> "Go Fish: d" h.keys #-> ["c", "d"]
[править] Hash#==
hsh == other_hash #-> true или false
Равенство — два хеша считаются равными, если они содержат одинаковое число ключей, и если каждая пара ключ-значение эквивалентна (согласно методу Object#==) соответствующим элементам в другом хеше.
h1 = { "a" => 1, "c" => 2 } h2 = { 7 => 35, "c" => 2, "a" => 1 } h3 = { "a" => 1, "c" => 2, 7 => 35 } h4 = { "a" => 1, "d" => 2, "f" => 35 } h1 == h2 #-> false h2 == h3 #-> true h3 == h4 #-> false
[править] Hash#[]
hsh[key] #-> value
Получение элемента — возвращает значение соответствующее ключу key. Если ключа не существует, то возвращается значение по-умолчанию (см. Hash::new).
h = { "a" => 100, "b" => 200 } h["a"] #-> 100 h["c"] #-> nil
[править] Hash#[]=
hsh[key] = value #-> value
Присваивание - ассоциирует значение value с ключем key.
h = { "a" => 100, "b" => 200 } h["a"] = 9 h["c"] = 4 h #-> {"a"=>9, "b"=>200, "c"=>4}
|
Данный метод и метод store — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#clear
hsh.clear #-> hsh
Удаляет все пары ключ-значение из хеша hsh.
h = { "a" => 100, "b" => 200 } #-> {"a"=>100, "b"=>200} h.clear #-> {}
[править] Hash#default
hsh.default(key=nil) #-> obj
Возвращает значение по-умолчанию, т.е. значение, которое будет возвращать hsh[key], если ключа key не существует в хеше hsh.
h = Hash.new #-> {} h.default #-> nil h.default(2) #-> nil h = Hash.new("cat") #-> {} h.default #-> "cat" h.default(2) #-> "cat" h = Hash.new {|h,k| h[k] = k.to_i*10} #-> {} h.default #-> 0 h.default(2) #-> 20
|
Полезно взглянуть также на методы Hash::new и Hash#default= |
[править] Hash#default=
hsh.default = obj #-> hsh
Устанавливает значение по-умолчанию, т.е. значение, которое возвращает hsh[key], если ключа key не существует в хеше hsh.
h = { "a" => 100, "b" => 200 } h.default = "Go fish" h["a"] #-> 100 h["z"] #-> "Go fish" # Это не сделает того, на что вы надеятесь... h.default = proc do |hash, key| hash[key] = key + key end h[2] #-> #<Proc:0x401b3948@-:6> h["cat"] #-> #<Proc:0x401b3948@-:6>
[править] Hash#default_proc
hsh.default_proc #-> anObject
Если метод Hash::new был вызван с блоком, то возвращает блок, иначе возвращает nil.
h = Hash.new {|h,k| h[k] = k*k } #-> {} p = h.default_proc #-> #<Proc:0x401b3d08@-:1> a = [] #-> [] p.call(a, 2) a #-> [nil, nil, 4]
[править] Hash#delete
hsh.delete(key) #-> value hsh.delete(key) {| key | block } #-> value
Удаляет пару ключ-значение из хеша hsh, которая соответствует ключу key. Возвращается значение, соответствующее ключу. Если ключ не был найден, тогда возвращается "значение по-умолчанию". Если используется конструкция с блоком и ключ не был найден, то возвращается результат выполнения блока block, которому передается ключ key.
h = { "a" => 100, "b" => 200 } h.delete("a") #-> 100 h.delete("z") #-> nil h.delete("z") { |el| "#{el} не найден" } #-> "z не найден"
[править] Hash#delete_if
hsh.delete_if {| key, value | block } #-> hsh
Удаляет все пары ключ-значение из хеша hsh для которых блок block вычисляет значение true.
h = { "a" => 100, "b" => 200, "c" => 300 } h.delete_if {|key, value| key >= "b" } #-> {"a"=>100}
[править] Hash#each
hsh.each {| key, value | block } #-> hsh
Вызывает блок для каждый пары ключ-значение хеша hsh и передает в блок текущую пару ключ-значение в виде массива из двух элементов. В виду семантических особенностей параметров блока, эти параметры могут быть представлены не массивом, а двумя элементами с различными именами. Еще существует метод each_pair, который чуть более эффективен для блоков с двумя параметрами.
h = { "a" => 100, "b" => 200 } h.each {|key, value| puts "#{key} => #{value}" }
результат:
a => 100 b => 200
[править] Hash#each_key
hsh.each_key {| key | block } #-> hsh
Выполняет блок block для каждого ключа в хеше hsh, передавая в блок ключ key в качестве параметра.
h = { "a" => 100, "b" => 200 } h.each_key {|key| puts key }
результат:
a b
[править] Hash#each_pair
hsh.each_pair {| key_value_array | block } #-> hsh
Выполняет блок block для каждого ключа в хеше hsh, передавая в блок ключ и значение в качестве параметров.
h = { "a" => 100, "b" => 200 } h.each_pair {|key, value| puts "#{key} => #{value}" }
результат:
a => 100 b => 200
[править] Hash#each_value
hsh.each_value {| value | block } #-> hsh
Выполняет блок block для каждого ключа в хеше hsh, передавая в блок значение value, соответствующее ключу, в качестве параметра.
h = { "a" => 100, "b" => 200 } h.each_value {|value| puts value }
результат:
100 200
[править] Hash#empty?
hsh.empty? #-> true или false
Возвращает true, если хеш hsh не содержит пар ключ-значение вовсе.
{}.empty? #-> true
[править] Hash#fetch
hsh.fetch(key [, default] ) #-> obj hsh.fetch(key) {| key | block } #-> obj
Возвращает значение, соответствующее ключу key. Если ключ не был найден, тогда есть несколько ситуаций: Без иных аргументов будет подниматься исключение IndexError; Если задан параметр default, тогда он и будет возвращен; Если конструкция определена с блоком, тогда будет выполняться блок, которому в качестве аргумента будет передан ключ.
h = { "a" => 100, "b" => 200 } h.fetch("a") #-> 100 h.fetch("z", "go fish") #-> "go fish" h.fetch("z") { |el| "go fish, #{el}"} #-> "go fish, z"
Следующий пример показывает, что если ключ не найден и значение по-умолчанию не поставляется, то поднимается исключение.
h = { "a" => 100, "b" => 200 } h.fetch("z")
результат:
prog.rb:2:in `fetch': key not found (IndexError) from prog.rb:2
[править] Hash#has_key?
hsh.has_key?(key) #-> true или false
Возвращает true, если заданный ключ находится в хеше hsh.
h = { "a" => 100, "b" => 200 } h.has_key?("a") #-> true h.has_key?("z") #-> false
|
Методы has_key?, include?, key? и member? — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#has_value?
hsh.has_value?(value) #-> true или false
Возвращает true, если заданное значение принадлежит некоторому ключу в хеше hsh.
h = { "a" => 100, "b" => 200 } h.has_value?(100) #-> true h.has_value?(999) #-> false
|
Методы has_value? и value? — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#include?
hsh.include?(key) #-> true или false
Возвращает true, если заданный ключ находится в хеше hsh.
h = { "a" => 100, "b" => 200 } h.include?("a") #-> true h.include?("z") #-> false
|
Методы include?, has_key?, key? и member? — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#index
hsh.index(value) #-> key
Возвращает ключ для заданного значения. Если значение не найдено, возвращает nil.
h = { "a" => 100, "b" => 200 } h.index(200) #-> "b" h.index(999) #-> nil
[править] Hash#indexes
hsh.indexes(key, ...) #-> array
|
Методы indexes и indices — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#indices
hsh.indices(key, ...) #-> array
|
Методы indices и indexes — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#inspect
hsh.inspect #-> string
Возвращает содержимое хеша в виде строки.
[править] Hash#invert
hsh.invert #-> aHash
Возвращает новый хеш, созданный путем использования значений хеша hsh в качестве ключей, а ключей в качестве значений.
h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 } h.invert #-> {0=>"a", 100=>"n", 200=>"d", 300=>"y"}
[править] Hash#key?
hsh.key?(key) #-> true или false
Возвращает true, если заданный ключ находится в хеше hsh.
h = { "a" => 100, "b" => 200 } h.key?("a") #-> true h.key?("z") #-> false
|
Методы key?, has_key?, include? и member? — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#keys
hsh.keys #-> array
Возвращает новый массив, состоящий из ключей данного хеша.
h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 } h.keys #-> ["a", "b", "c", "d"]
|
Полезно посмотреть на метод values, который имеет схожую функциональность |
[править] Hash#length
hsh.length #-> fixnum
Возвращает количество пар ключ-значение в данном хеше.
h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 } h.length #-> 4 h.delete("a") #-> 200 h.length #-> 3
|
Методы length и size — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#member?
hsh.member?(key) #-> true или false
Возвращает true, если заданный ключ находится в хеше hsh.
h = { "a" => 100, "b" => 200 } h.member?("a") #-> true h.member?("z") #-> false
|
Методы member?, has_key?, include? и key? — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#merge
hsh.merge(other_hash) #-> a_hash hsh.merge(other_hash){|key, oldval, newval| block} #-> a_hash
Возвращает новый хеш, который состоит из содержимого хешей other_hash и hsh. Если в результате слияния обнаружатся одинаковые ключи, то для него будет записано значение из хеша other_hash (если задан блок, то будет записано значение, которое получится в результате выполнения блока).
h1 = { "a" => 100, "b" => 200 } h2 = { "b" => 254, "c" => 300 } h1.merge(h2) #=> {"a"=>100, "b"=>254, "c"=>300} h1 #=> {"a"=>100, "b"=>200}
[править] Hash#merge!
hsh.merge!(other_hash) #-> hsh hsh.update(other_hash) #-> hsh hsh.merge!(other_hash){|key, oldval, newval| block} #-> hsh hsh.update(other_hash){|key, oldval, newval| block} #-> hsh
Добавляет содержимое хеша other_hash к хешу hsh. Если обнаружатся дублирующие ключи, то значение для него будет взято из other_hash (или получено в результате выполнения блока, если он задан).
h1 = { "a" => 100, "b" => 200 } h2 = { "b" => 254, "c" => 300 } h1.merge!(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
|
Методы megre! и update — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#rehash
hsh.rehash #-> hsh
Если ключами хеша являются переменные, то может возникнуть ситуация, когда их значение меняется. Чтобы иметь доступ к ассоциированным с ними данным нужно вызвать данный метод, чтобы он привел ключи в соответствие с новым значеним переменных. Если метод вызывается, в то время как итератор обходит этот самый хеш, то будет возбуждена ошибка вида IndexError.
a = [ "a", "b" ] c = [ "c", "d" ] h = { a => 100, c => 300 } h[a] #-> 100 a[0] = "z" h[a] #-> nil h.rehash #-> {["z", "b"]=>100, ["c", "d"]=>300} h[a] #-> 100
[править] Hash#reject
hsh.reject {| key, value | block } #-> a_hash
То же самое, что и метод delete_if, но обрабатывает (и возвращает) копию хеша hsh. По сути, данный метод эквивалентен hsh.dup.delete_if.
[править] Hash#reject!
hsh.reject! {| key, value | block } #-> hsh или nil
Эквивалентно delete_if, но возвращает nil, если хеш не был изменен в результате работы данного метода.
[править] Hash#replace
hsh.replace(other_hash) #-> hsh
Заменяет содержимое хеша hsh на содержимое хеша other_hash.
h = { "a" => 100, "b" => 200 } h.replace({ "c" => 300, "d" => 400 }) #-> {"c"=>300, "d"=>400}
[править] Hash#select
hsh.select {|key, value| block} #-> array
Возвращает новый массив, состоящий из пар [ключ, значение], для которых блок вычисляет значение true.
h = { "a" => 100, "b" => 200, "c" => 300 } h.select {|k,v| k > "a"} #-> [["b", 200], ["c", 300]] h.select {|k,v| v < 200} #-> [["a", 100]]
|
Полезно посмотреть на метод values_at, который имеет схожую функциональность |
[править] Hash#shift
hsh.shift #-> anArray или obj
Удаляет пару ключ-значение из хеша hsh и возвращает эту пару в виде массива [ key, value ]. Если хеш пуст, то возвращает значение по-умолчанию.
h = { 1 => "a", 2 => "b", 3 => "c" } h.shift #-> [1, "a"] h #-> {2=>"b", 3=>"c"}
[править] Hash#size
hsh.size #-> fixnum
Возвращает количество пар ключ-значение в данном хеше.
h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 } h.size #-> 4 h.delete("a") #-> 200 h.size #-> 3
|
Методы size и length — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#sort
hsh.sort #-> array hsh.sort {| a, b | block } #-> array
Преобразует хеш hsh в массив массивов - [ key, value ] и сортирует его, используя Array#sort.
h = { "a" => 20, "b" => 30, "c" => 10 } h.sort #-> [["a", 20], ["b", 30], ["c", 10]] h.sort {|a,b| a[1]<=>b[1]} #-> [["c", 10], ["a", 20], ["b", 30]]
[править] Hash#store
hsh.store(key, value) #-> value
Присваивание - ассоциирует значение value с ключем key. Идентичен методу []=.
h = { "a" => 100, "b" => 200 } h.store("a", 9) h.store("c", 4) h #-> {"a"=>9, "b"=>200, "c"=>4}
[править] Hash#to_a
hsh.to_a #-> array
Конвертирует хеш hsh в массив, состоящий из массивов [ key, value ].
h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 } h.to_a #-> [["a", 100], ["c", 300], ["d", 400]]
[править] Hash#to_hash
hsh.to_hash #-> hsh
Возвращает hsh.
[править] Hash#to_s
hsh.to_s #-> string
Преобразует хеш hsh в строку путем преобразования хеша в массив массивов [ key, value ], и преобразования этого массива в строку, используя Array#join со стандартным разделителем.
h = { "c" => 300, "a" => 100, "d" => 400 } h.to_s #-> "a100c300d400"
[править] Hash#update
hsh.merge!(other_hash) #-> hsh hsh.update(other_hash) #-> hsh hsh.merge!(other_hash){|key, oldval, newval| block} #-> hsh hsh.update(other_hash){|key, oldval, newval| block} #-> hsh
Добавляет содержимое хеша other_hash к хешу hsh. Если обнаружатся дублирующие ключи, то значение для него будет взято из other_hash (или получено в результате выполнения блока, если он задан).
h1 = { "a" => 100, "b" => 200 } h2 = { "b" => 254, "c" => 300 } h1.update(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
|
Методы megre! и update — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#value?
hsh.value?(value) #-> true или false
Возвращает true, если заданное значение принадлежит некоторому ключу в хеше hsh.
h = { "a" => 100, "b" => 200 } h.value?(100) #-> true h.value?(999) #-> false
|
Методы value? и has_value? — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Hash#values
hsh.values #-> array
Возвращает новый массив, состоящий из значений данного хеша.
h = { "a" => 100, "b" => 200, "c" => 300 } h.values #=> [100, 200, 300]
|
Полезно посмотреть на метод keys, который имеет схожую функциональность |
[править] Hash#values_at
hsh.values_at(key, ...) #-> array
Возвращает массив содержащий значения, соответствующие заданным ключам. (См. Hash.select).
h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" } h.values_at("cow", "cat") #-> ["bovine", "feline"]
[править] Класс IO
Class IO is the basis for all input and output in Ruby. An I/O stream may be duplexed (that is, bidirectional), and so may use more than one native operating system stream. Many of the examples in this section use class File, the only standard subclass of IO. The two classes are closely associated. As used in this section, portname may take any of the following forms.
- A plain string represents a filename suitable for the underlying operating system.
- A string starting with ``| indicates a subprocess. The remainder of the string following the ``| is invoked as a process with appropriate input/output channels connected to it.
- A string equal to ``|- will create another Ruby instance as a subprocess.
Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename ``/gumby/ruby/test.rb will be opened as ``\gumby\ruby\test.rb. When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:
"c:\gumby\ruby\test.rb"
Our examples here will use the Unix-style forward slashes; File::SEPARATOR can be used to get the platform-specific separator character. I/O ports may be opened in any one of several different modes, which are shown in this section as mode. The mode may either be a Fixnum or a String. If numeric, it should be one of the operating system specific constants (O_RDONLY, O_WRONLY, O_RDWR, O_APPEND and so on). See man open(2) for more information. If the mode is given as a String, it must be one of the values listed in the following table.
Mode | Meaning
-----+--------------------------------------------------------
"r" | Read-only, starts at beginning of file (default mode).
-----+--------------------------------------------------------
"r+" | Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w" | Write-only, truncates existing file
| to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" | Read-write, truncates existing file to zero length
| or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a" | Write-only, starts at end of file if file exists,
| otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" | Read-write, starts at end of file if file exists,
| otherwise creates a new file for reading and
| writing.
-----+--------------------------------------------------------
"b" | (DOS/Windows only) Binary file mode (may appear with
| any of the key letters listed above).
The global constant ARGF (also accessible as $<) provides an IO-like stream which allows access to all files mentioned on the command line (or STDIN if no files are mentioned). ARGF provides the methods #path and #filename to access the name of the file currently being read.
Примеси
Enumerable (all?, any?, collect, detect, each_cons, each_slice, each_with_index, entries, enum_cons, enum_slice, enum_with_index, find, find_all, grep, group_by, include?, index_by, inject, map, max, member?, min, partition, reject, select, sort, sort_by, sum, to_a, to_set, zip),
Константы
SEEK_CUR, SEEK_END, SEEK_SET
Методы класса
for_fd, foreach, new, new, open, pipe, popen, readlines, read, select, sysopen
Методы объекта
<<, binmode, block_scanf, close_read, close_write, closed?, close, each_byte, each_line, each, eof?, eof, fcntl, fileno, flush, fsync, getc, gets, inspect, ioctl, isatty, lineno=, lineno, pid, pos=, pos, printf, print, putc, puts, read_nonblock, readbytes, readchar, readlines, readline, readpartial, read, reopen, rewind, scanf, seek, soak_up_spaces, stat, sync=, sync, sysread, sysseek, syswrite, tell, to_io, to_i, tty?, ungetc, write_nonblock, write
[править] IO::for_fd
IO.for_fd(fd, mode) => io
Synonym for IO::new.
[править] IO::foreach
IO.foreach(name, sep_string=$/) {|line| block } => nil
Executes the block for every line in the named I/O port, where lines are separated by sep_string.
IO.foreach("testfile") {|x| print "GOT ", x }
produces:
GOT This is line one
GOT This is line two
GOT This is line three
GOT And so on...
[править] IO::new
IO.new(fd, mode_string) => io
Returns a new IO object (a stream) for the given integer file descriptor and mode string. See also IO#fileno and IO::for_fd.
a = IO.new(2,"w") # '2' is standard error
$stderr.puts "Hello"
a.puts "World"
produces:
Hello
World
[править] IO::new
IO.new(fd, mode_string) => io
Returns a new IO object (a stream) for the given integer file descriptor and mode string. See also IO#fileno and IO::for_fd.
a = IO.new(2,"w") # '2' is standard error
$stderr.puts "Hello"
a.puts "World"
produces:
Hello
World
[править] IO::open
IO.open(fd, mode_string="r" ) => io
IO.open(fd, mode_string="r" ) {|io| block } => obj
With no associated block, open is a synonym for IO::new. If the optional code block is given, it will be passed io as an argument, and the IO object will automatically be closed when the block terminates. In this instance, IO::open returns the value of the block.
[править] IO::pipe
IO.pipe -> array
Creates a pair of pipe endpoints (connected to each other) and returns them as a two-element array of IO objects: [ read_file, write_file ]. Not available on all platforms. In the example below, the two processes close the ends of the pipe that they are not using. This is not just a cosmetic nicety. The read end of a pipe will not generate an end of file condition if there are any writers with the pipe still open. In the case of the parent process, the rd.read will never return if it does not first issue a wr.close.
rd, wr = IO.pipe if fork wr.close puts "Parent got: <#{rd.read}>" rd.close Process.wait else rd.close puts "Sending message to parent" wr.write "Hi Dad" wr.close end
produces:
Sending message to parent
Parent got: <Hi Dad>
[править] IO::popen
IO.popen(cmd_string, mode="r" ) => io
IO.popen(cmd_string, mode="r" ) {|io| block } => obj
Runs the specified command string as a subprocess; the subprocess's standard input and output will be connected to the returned IO object. If cmd_string starts with a ``-, then a new instance of Ruby is started as the subprocess. The default mode for the new file object is ``r, but mode may be set to any of the modes listed in the description for class IO. If a block is given, Ruby will run the command as a child connected to Ruby with a pipe. Ruby's end of the pipe will be passed as a parameter to the block. At the end of block, Ruby close the pipe and sets $?. In this case IO::popen returns the value of the block. If a block is given with a cmd_string of ``-, the block will be run in two separate processes: once in the parent, and once in a child. The parent process will be passed the pipe object as a parameter to the block, the child version of the block will be passed nil, and the child's standard in and standard out will be connected to the parent through the pipe. Not available on all platforms.
f = IO.popen("uname")
p f.readlines
puts "Parent is #{Process.pid}"
IO.popen ("date") { |f| puts f.gets }
IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f}"}
p $?
produces:
["Linux\n"]
Parent is 26166
Wed Apr 9 08:53:52 CDT 2003
26169 is here, f is
26166 is here, f is #<IO:0x401b3d44>
#<Process::Status: pid=26166,exited(0)>
[править] IO::read
IO.read(name, [length [, offset]] ) => string
Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.
IO.read("testfile") #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
IO.read("testfile", 20) #=> "This is line one\nThi"
IO.read("testfile", 20, 10) #=> "ne one\nThis is line "
[править] IO::readlines
IO.readlines(name, sep_string=$/) => array
Reads the entire file specified by name as individual lines, and returns those lines in an array. Lines are separated by sep_string.
a = IO.readlines("testfile")
a[0] #=> "This is line one\n"
[править] IO::select
IO.select(read_array [, write_array [, error_array [, timeout]]] ) => array or nil
See Kernel#select.
[править] IO::sysopen
IO.sysopen(path, [mode, [perm]]) => fixnum
Opens the given path, returning the underlying file descriptor as a Fixnum.
IO.sysopen("testfile") #=> 3
[править] IO#<<
ios << obj => ios
String Output---Writes obj to ios. obj will be converted to a string using to_s.
$stdout << "Hello " << "world!\n"
produces:
Hello world!
[править] IO#binmode
ios.binmode => ios
Puts ios into binary mode. This is useful only in MS-DOS/Windows environments. Once a stream is in binary mode, it cannot be reset to nonbinary mode.
[править] IO#block_scanf
block_scanf(str) {|current| ...}
(нет описания...)
[править] IO#close
ios.close => nil
Closes ios and flushes any pending writes to the operating system. The stream is unavailable for any further data operations; an IOError is raised if such an attempt is made. I/O streams are automatically closed when they are claimed by the garbage collector. If ios is opened by IO.popen, close sets $?.
[править] IO#close_read
ios.close_read => nil
Closes the read end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe). Will raise an IOError if the stream is not duplexed.
f = IO.popen("/bin/sh","r+")
f.close_read
f.readlines
produces:
prog.rb:3:in `readlines': not opened for reading (IOError)
from prog.rb:3
[править] IO#close_write
ios.close_write => nil
Closes the write end of a duplex I/O stream (i.e., one that contains both a read and a write stream, such as a pipe). Will raise an IOError if the stream is not duplexed.
f = IO.popen("/bin/sh","r+")
f.close_write
f.print "nowhere"
produces:
prog.rb:3:in `write': not opened for writing (IOError)
from prog.rb:3:in `print'
from prog.rb:3
[править] IO#closed?
ios.closed? => true or false
Returns true if ios is completely closed (for duplex streams, both reader and writer), false otherwise.
f = File.new("testfile")
f.close #=> nil
f.closed? #=> true
f = IO.popen("/bin/sh","r+")
f.close_write #=> nil
f.closed? #=> false
f.close_read #=> nil
f.closed? #=> true
[править] IO#each
ios.each(sep_string=$/) {|line| block } => ios
ios.each_line(sep_string=$/) {|line| block } => ios
Executes the block for every line in ios, where lines are separated by sep_string. ios must be opened for reading or an IOError will be raised.
f = File.new("testfile")
f.each {|line| puts "#{f.lineno}: #{line}" }
produces:
1: This is line one
2: This is line two
3: This is line three
4: And so on...
[править] IO#each_byte
ios.each_byte {|byte| block } => nil
Calls the given block once for each byte (0..255) in ios, passing the byte as an argument. The stream must be opened for reading or an IOError will be raised.
f = File.new("testfile")
checksum = 0
f.each_byte {|x| checksum ^= x } #=> #<File:testfile>
checksum #=> 12
[править] IO#each_line
ios.each(sep_string=$/) {|line| block } => ios
ios.each_line(sep_string=$/) {|line| block } => ios
Executes the block for every line in ios, where lines are separated by sep_string. ios must be opened for reading or an IOError will be raised.
f = File.new("testfile")
f.each {|line| puts "#{f.lineno}: #{line}" }
produces:
1: This is line one
2: This is line two
3: This is line three
4: And so on...
[править] IO#eof
ios.eof => true or false ios.eof? => true or false
Returns true if ios is at end of file that means there are no more data to read. The stream must be opened for reading or an IOError will be raised.
f = File.new("testfile")
dummy = f.readlines
f.eof #=> true
If ios is a stream such as pipe or socket, IO#eof? blocks until the other end sends some data or closes it.
r, w = IO.pipe
Thread.new { sleep 1; w.close }
r.eof? #=> true after 1 second blocking
r, w = IO.pipe
Thread.new { sleep 1; w.puts "a" }
r.eof? #=> false after 1 second blocking
r, w = IO.pipe
r.eof? # blocks forever
Note that IO#eof? reads data to a input buffer. So IO#sysread doesn't work with IO#eof?.
[править] IO#eof?
ios.eof => true or false ios.eof? => true or false
Returns true if ios is at end of file that means there are no more data to read. The stream must be opened for reading or an IOError will be raised.
f = File.new("testfile")
dummy = f.readlines
f.eof #=> true
If ios is a stream such as pipe or socket, IO#eof? blocks until the other end sends some data or closes it.
r, w = IO.pipe
Thread.new { sleep 1; w.close }
r.eof? #=> true after 1 second blocking
r, w = IO.pipe
Thread.new { sleep 1; w.puts "a" }
r.eof? #=> false after 1 second blocking
r, w = IO.pipe
r.eof? # blocks forever
Note that IO#eof? reads data to a input buffer. So IO#sysread doesn't work with IO#eof?.
[править] IO#fcntl
ios.fcntl(integer_cmd, arg) => integer
Provides a mechanism for issuing low-level commands to control or query file-oriented I/O streams. Arguments and results are platform dependent. If arg is a number, its value is passed directly. If it is a string, it is interpreted as a binary sequence of bytes (Array#pack might be a useful way to build this string). On Unix platforms, see fcntl(2) for details. Not implemented on all platforms.
[править] IO#fileno
ios.fileno => fixnum ios.to_i => fixnum
Returns an integer representing the numeric file descriptor for ios.
$stdin.fileno #=> 0
$stdout.fileno #=> 1
(еще известен как to_i)
[править] IO#flush
ios.flush => ios
Flushes any buffered data within ios to the underlying operating system (note that this is Ruby internal buffering only; the OS may buffer the data as well).
$stdout.print "no newline"
$stdout.flush
produces:
no newline
[править] IO#fsync
ios.fsync => 0 or nil
Immediately writes all buffered data in ios to disk. Returns nil if the underlying operating system does not support fsync(2). Note that fsync differs from using IO#sync=. The latter ensures that data is flushed from Ruby's buffers, but doesn't not guarantee that the underlying operating system actually writes it to disk.
[править] IO#getc
ios.getc => fixnum or nil
Gets the next 8-bit byte (0..255) from ios. Returns nil if called at end of file.
f = File.new("testfile")
f.getc #=> 84
f.getc #=> 104
[править] IO#gets
ios.gets(sep_string=$/) => string or nil
Reads the next ``line from the I/O stream; lines are separated by sep_string. A separator of nil reads the entire contents, and a zero-length separator reads the input a paragraph at a time (two successive newlines in the input separate paragraphs). The stream must be opened for reading or an IOError will be raised. The line read in will be returned and also assigned to $_. Returns nil if called at end of file.
File.new("testfile").gets #=> "This is line one\n"
$_ #=> "This is line one\n"
[править] IO#inspect
ios.inspect => string
Return a string describing this IO object.
[править] IO#ioctl
ios.ioctl(integer_cmd, arg) => integer
Provides a mechanism for issuing low-level commands to control or query I/O devices. Arguments and results are platform dependent. If arg is a number, its value is passed directly. If it is a string, it is interpreted as a binary sequence of bytes. On Unix platforms, see ioctl(2) for details. Not implemented on all platforms.
[править] IO#isatty
ios.isatty => true or false ios.tty? => true or false
Returns true if ios is associated with a terminal device (tty), false otherwise.
File.new("testfile").isatty #=> false
File.new("/dev/tty").isatty #=> true
[править] IO#lineno
ios.lineno => integer
Returns the current line number in ios. The stream must be opened for reading. lineno counts the number of times gets is called, rather than the number of newlines encountered. The two values will differ if gets is called with a separator other than newline. See also the $. variable.
f = File.new("testfile")
f.lineno #=> 0
f.gets #=> "This is line one\n"
f.lineno #=> 1
f.gets #=> "This is line two\n"
f.lineno #=> 2
[править] IO#lineno=
ios.lineno = integer => integer
Manually sets the current line number to the given value. $. is updated only on the next read.
f = File.new("testfile")
f.gets #=> "This is line one\n"
$. #=> 1
f.lineno = 1000
f.lineno #=> 1000
$. # lineno of last read #=> 1
f.gets #=> "This is line two\n"
$. # lineno of last read #=> 1001
[править] IO#pid
ios.pid => fixnum
Returns the process ID of a child process associated with ios. This will be set by IO::popen.
pipe = IO.popen("-")
if pipe
$stderr.puts "In parent, child pid is #{pipe.pid}"
else
$stderr.puts "In child, pid is #{$$}"
end
produces:
In child, pid is 26209
In parent, child pid is 26209
[править] IO#pos
ios.pos => integer ios.tell => integer
Returns the current offset (in bytes) of ios.
f = File.new("testfile")
f.pos #=> 0
f.gets #=> "This is line one\n"
f.pos #=> 17
[править] IO#pos=
ios.pos = integer => integer
Seeks to the given position (in bytes) in ios.
f = File.new("testfile")
f.pos = 17
f.gets #=> "This is line two\n"
[править] IO#print
ios.print() => nil ios.print(obj, ...) => nil
Writes the given object(s) to ios. The stream must be opened for writing. If the output record separator ($\) is not nil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren't strings will be converted by calling their to_s method. With no argument, prints the contents of the variable $_. Returns nil.
$stdout.print("This is ", 100, " percent.\n")
produces:
This is 100 percent.
[править] IO#printf
ios.printf(format_string [, obj, ...] ) => nil
Formats and writes to ios, converting parameters under control of the format string. See Kernel#sprintf for details.
[править] IO#putc
ios.putc(obj) => obj
If obj is Numeric, write the character whose code is obj, otherwise write the first character of the string representation of obj to ios.
$stdout.putc "A"
$stdout.putc 65
produces:
AA
[править] IO#puts
ios.puts(obj, ...) => nil
Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.
$stdout.puts("this", "is", "a", "test")
produces:
this
is
a
test
[править] IO#read
ios.read([length [, buffer]]) => string, buffer, or nil
Reads at most length bytes from the I/O stream, or to the end of file if length is omitted or is nil. length must be a non-negative integer or nil. If the optional buffer argument is present, it must reference a String, which will receive the data. At end of file, it returns nil or "" depend on length. ios.read() and ios.read(nil) returns "". ios.read(positive-integer) returns nil.
f = File.new("testfile")
f.read(16) #=> "This is line one"
[править] IO#read_nonblock
ios.read_nonblock(maxlen) => string ios.read_nonblock(maxlen, outbuf) => outbuf
Reads at most maxlen bytes from ios using read(2) system call after O_NONBLOCK is set for the underlying file descriptor. If the optional outbuf argument is present, it must reference a String, which will receive the data. read_nonblock just calls read(2). It causes all errors read(2) causes: EAGAIN, EINTR, etc. The caller should care such errors. read_nonblock causes EOFError on EOF. If the read buffer is not empty, read_nonblock reads from the buffer like readpartial. In this case, read(2) is not called.
[править] IO#readbytes
readbytes(n)
Reads exactly n bytes. If the data read is nil an EOFError is raised. If the data read is too short a TruncatedDataError is raised and the read data is obtainable via its #data method.
[править] IO#readchar
ios.readchar => fixnum
Reads a character as with IO#getc, but raises an EOFError on end of file.
[править] IO#readline
ios.readline(sep_string=$/) => string
Reads a line as with IO#gets, but raises an EOFError on end of file.
[править] IO#readlines
ios.readlines(sep_string=$/) => array
Reads all of the lines in ios, and returns them in anArray. Lines are separated by the optional sep_string. If sep_string is nil, the rest of the stream is returned as a single record. The stream must be opened for reading or an IOError will be raised.
f = File.new("testfile")
f.readlines[0] #=> "This is line one\n"
[править] IO#readpartial
ios.readpartial(maxlen) => string ios.readpartial(maxlen, outbuf) => outbuf
Reads at most maxlen bytes from the I/O stream. It blocks only if ios has no data immediately available. It doesn't block if some data available. If the optional outbuf argument is present, it must reference a String, which will receive the data. It raises EOFError on end of file. readpartial is designed for streams such as pipe, socket, tty, etc. It blocks only when no data immediately available. This means that it blocks only when following all conditions hold.
- the buffer in the IO object is empty.
- the content of the stream is empty.
- the stream is not reached to EOF.
When readpartial blocks, it waits data or EOF on the stream. If some data is reached, readpartial returns with the data. If EOF is reached, readpartial raises EOFError. When readpartial doesn't blocks, it returns or raises immediately. If the buffer is not empty, it returns the data in the buffer. Otherwise if the stream has some content, it returns the data in the stream. Otherwise if the stream is reached to EOF, it raises EOFError.
r, w = IO.pipe # buffer pipe content
w << "abc" # "" "abc".
r.readpartial(4096) #=> "abc" "" ""
r.readpartial(4096) # blocks because buffer and pipe is empty.
r, w = IO.pipe # buffer pipe content
w << "abc" # "" "abc"
w.close # "" "abc" EOF
r.readpartial(4096) #=> "abc" "" EOF
r.readpartial(4096) # raises EOFError
r, w = IO.pipe # buffer pipe content
w << "abc\ndef\n" # "" "abc\ndef\n"
r.gets #=> "abc\n" "def\n" ""
w << "ghi\n" # "def\n" "ghi\n"
r.readpartial(4096) #=> "def\n" "" "ghi\n"
r.readpartial(4096) #=> "ghi\n" "" ""
Note that readpartial behaves similar to sysread. The differences are:
- If the buffer is not empty, read from the buffer instead of "sysread for buffered IO (IOError)".
- It doesn't cause Errno::EAGAIN and Errno::EINTR. When readpartial meets EAGAIN and EINTR by read system call, readpartial retry the system call.
The later means that readpartial is nonblocking-flag insensitive. It blocks on the situation IO#sysread causes Errno::EAGAIN as if the fd is blocking mode.
[править] IO#reopen
ios.reopen(other_IO) => ios ios.reopen(path, mode_str) => ios
Reassociates ios with the I/O stream given in other_IO or to a new stream opened on path. This may dynamically change the actual class of this stream.
f1 = File.new("testfile")
f2 = File.new("testfile")
f2.readlines[0] #=> "This is line one\n"
f2.reopen(f1) #=> #<File:testfile>
f2.readlines[0] #=> "This is line one\n"
[править] IO#rewind
ios.rewind => 0
Positions ios to the beginning of input, resetting lineno to zero.
f = File.new("testfile")
f.readline #=> "This is line one\n"
f.rewind #=> 0
f.lineno #=> 0
f.readline #=> "This is line one\n"
[править] IO#scanf
scanf(str,&b)
The trick here is doing a match where you grab one line of input at a time. The linebreak may or may not occur at the boundary where the string matches a format specifier. And if it does, some rule about whitespace may or may not be in effect... That's why this is much more elaborate than the string version. For each line: Match succeeds (non-emptily) and the last attempted spec/string sub-match succeeded:
could the last spec keep matching?
yes: save interim results and continue (next line)
The last attempted spec/string did not match: are we on the next-to-last spec in the string?
yes:
is fmt_string.string_left all spaces?
yes: does current spec care about input space?
yes: fatal failure
no: save interim results and continue
no: continue [this state could be analyzed further]
[править] IO#seek
ios.seek(amount, whence=SEEK_SET) -> 0
Seeks to a given offset anInteger in the stream according to the value of whence:
IO::SEEK_CUR | Seeks to amount plus current position
--------------+----------------------------------------------------
IO::SEEK_END | Seeks to amount plus end of stream (you probably
| want a negative value for amount)
--------------+----------------------------------------------------
IO::SEEK_SET | Seeks to the absolute location given by amount
Example:
f = File.new("testfile")
f.seek(-13, IO::SEEK_END) #=> 0
f.readline #=> "And so on...\n"
[править] IO#soak_up_spaces
soak_up_spaces()
(нет описания...)
[править] IO#stat
ios.stat => stat
Returns status information for ios as an object of type File::Stat.
f = File.new("testfile")
s = f.stat
"%o" % s.mode #=> "100644"
s.blksize #=> 4096
s.atime #=> Wed Apr 09 08:53:54 CDT 2003
[править] IO#sync
ios.sync => true or false
Returns the current ``sync mode of ios. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered by Ruby internally. See also IO#fsync.
f = File.new("testfile")
f.sync #=> false
[править] IO#sync=
ios.sync = boolean => boolean
Sets the ``sync mode to true or false. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered internally. Returns the new state. See also IO#fsync.
f = File.new("testfile")
f.sync = true
(produces no output)
[править] IO#sysread
ios.sysread(integer ) => string
Reads integer bytes from ios using a low-level read and returns them as a string. Do not mix with other methods that read from ios or you may get unpredictable results. Raises SystemCallError on error and EOFError at end of file.
f = File.new("testfile")
f.sysread(16) #=> "This is line one"
[править] IO#sysseek
ios.sysseek(offset, whence=SEEK_SET) => integer
Seeks to a given offset in the stream according to the value of whence (see IO#seek for values of whence). Returns the new offset into the file.
f = File.new("testfile")
f.sysseek(-13, IO::SEEK_END) #=> 53
f.sysread(10) #=> "And so on."
[править] IO#syswrite
ios.syswrite(string) => integer
Writes the given string to ios using a low-level write. Returns the number of bytes written. Do not mix with other methods that write to ios or you may get unpredictable results. Raises SystemCallError on error.
f = File.new("out", "w")
f.syswrite("ABCDEF") #=> 6
[править] IO#tell
ios.pos => integer ios.tell => integer
Returns the current offset (in bytes) of ios.
f = File.new("testfile")
f.pos #=> 0
f.gets #=> "This is line one\n"
f.pos #=> 17
[править] IO#to_i
to_i()
Alias for #fileno
[править] IO#to_io
ios.to_io -> ios
Returns ios.
[править] IO#tty?
ios.isatty => true or false ios.tty? => true or false
Returns true if ios is associated with a terminal device (tty), false otherwise.
File.new("testfile").isatty #=> false
File.new("/dev/tty").isatty #=> true
[править] IO#ungetc
ios.ungetc(integer) => nil
Pushes back one character (passed as a parameter) onto ios, such that a subsequent buffered read will return it. Only one character may be pushed back before a subsequent read operation (that is, you will be able to read only the last of several characters that have been pushed back). Has no effect with unbuffered reads (such as IO#sysread).
f = File.new("testfile") #=> #<File:testfile>
c = f.getc #=> 84
f.ungetc(c) #=> nil
f.getc #=> 84
[править] IO#write
ios.write(string) => integer
Writes the given string to ios. The stream must be opened for writing. If the argument is not a string, it will be converted to a string using to_s. Returns the number of bytes written.
count = $stdout.write( "This is a test\n" )
puts "That was #{count} bytes of data"
produces:
This is a test
That was 15 bytes of data
[править] IO#write_nonblock
ios.write_nonblock(string) => integer
Writes the given string to ios using write(2) system call after O_NONBLOCK is set for the underlying file descriptor. write_nonblock just calls write(2). It causes all errors write(2) causes: EAGAIN, EINTR, etc. The result may also be smaller than string.length (partial write). The caller should care such errors and partial write.
[править] Класс Integer < Numeric
Integer — это родительский класс для классов Bignum и Fixnum, которые отвечают за работу с целыми числами.
Примеси
Precision (prec, prec_f, prec_i)
Методы класса
from_prime_division, induced_from
Методы объекта
ceil, chr, denominator, downto, floor, gcdlcm, gcd, integer?, lcm, next, numerator, prime_division, round, succ, times, to_int, to_i, to_r, truncate, upto
[править] Integer::from_prime_division
Integer::from_prime_division( ''array'' ) #-> integer
Преобразует двумерный массив array из простых делителей и их степеней обратно в целое число.
require 'mathn' Integer.from_prime_division( [[5,1], [7,1]] ) #-> 35 Integer.from_prime_division( 122.prime_division ) #-> 122
|
Полезно посмотреть на метод prime_division, который имеет схожую функциональность |
[править] Integer::induced_from
Integer.induced_from(obj) #-> integer
Преобразует obj в целое число.
[править] Integer#ceil
int.to_i #-> int int.to_int #-> int int.floor #-> int int.ceil #-> int int.round #-> int int.truncate #-> int
В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.
|
Полезно посмотреть на методы ceil, floor, round, to_i, to_int и truncate, которые имеют схожую функциональность |
[править] Integer#chr
int.chr #-> string
Возвращает строку, состоящую из ASCII-символа с кодом равным значению int.
65.chr #-> "A" ?a.chr #=> "a" 230.chr #=> "\346"
[править] Integer#denominator
num.denominator #-> 1
Для целого числа знаменатель всегда равен 1. Поэтому, данный метод возвращает 1.
[править] Integer#downto
int.downto(limit) {|i| block } #-> int
Выполняет блок для всех чисел с int по limit с шагом -1 (то есть число int должно быть больше числа limit).
5.downto(1) { |n| print n, ".. " } print " Liftoff!\n"
результат:
5.. 4.. 3.. 2.. 1.. Liftoff!
[править] Integer#floor
int.to_i #-> int int.to_int #-> int int.floor #-> int int.ceil #-> int int.round #-> int int.truncate #-> int
В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.
|
Полезно посмотреть на методы ceil, floor, round, to_i, to_int и truncate, которые имеют схожую функциональность |
[править] Integer#gcd
num.gcd(other)
Возвращает наибольший общий делитель двух чисел (num и other).
72.gcd 168 #-> 24 19.gcd 36 #-> 1
|
Результат данного метода — положительное целое число, независимо от знака аргументов |
|
Полезно посмотреть на методы gcd и gcdlcm, которые имеют схожую функциональность |
[править] Integer#gcdlcm
num.gcdlcm(other)
Возвращает НОД и НОК (см. gcd и lcm) двух чисел (num и other). Этот метод особенно эффективен, когда необходимо посчитать НОД и НОК одновременно.
6.gcdlcm 9 #-> [3, 18]
|
Полезно посмотреть на методы gcd и lcm, которые имеют схожую функциональность |
[править] Integer#integer?
int.integer? #-> true
Всегда возвращает true.
[править] Integer#lcm
num.lcm(other) #-> integer
Возвращает наименьшее общее кратное двух чисел (num и other).
6.lcm 7 #-> 42 6.lcm 9 #-> 18
|
Результат данного метода — положительное целое число, независимо от знака каждого из аргументов |
|
Полезно посмотреть на методы gcd и gcdlcm, которые имеют схожую функциональность |
[править] Integer#next
int.next #-> integer int.succ #-> integer
Возвращает целое число, которое равно int + 1.
1.next #-> 2 (-1).next #-> 0
|
Методы succ и next — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Integer#numerator
num.numerator #-> num
Для целого числа числитель всегда равен его значению. Поэтому данный метод возвращает значение num.
|
Полезно посмотреть на метод denominator, который имеет схожую функциональность |
[править] Integer#prime_division
num.prime_division #-> array
Возвращает двумерный массив, состоящий из простых делителей числа и их степеней.
require 'mathn' 35.prime_division #-> [[5, 1], [7, 1]] 256.prime_division #-> [[2, 8]]
|
Полезно посмотреть на метод from_prime_division, который имеет схожую функциональность |
[править] Integer#round
int.to_i #-> int int.to_int #-> int int.floor #-> int int.ceil #-> int int.round #-> int int.truncate #-> int
В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.
|
Полезно посмотреть на методы ceil, floor, round, to_i, to_int и truncate, которые имеют схожую функциональность |
[править] Integer#succ
int.next #-> integer int.succ #-> integer
Возвращает целое число, которое равно int + 1.
1.next #-> 2 (-1).next #-> 0
|
Методы succ и next — абсолютно идентичны, то есть являются именами одного и того же метода |
[править] Integer#times
int.times {|i| block } #-> int
Выполняет блок int раз, передавая в него значения от 0 до int - 1.
5.times do |i| print i, " " end
результат:
0 1 2 3 4
[править] Integer#to_i
int.to_i #-> int int.to_int #-> int int.floor #-> int int.ceil #-> int int.round #-> int int.truncate #-> int
В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.
|
Полезно посмотреть на методы ceil, floor, round, to_i, to_int и truncate, которые имеют схожую функциональность |
[править] Integer#to_int
int.to_i #-> int int.to_int #-> int int.floor #-> int int.ceil #-> int int.round #-> int int.truncate #-> int
В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.
|
Полезно посмотреть на методы ceil, floor, round, to_i, to_int и truncate, которые имеют схожую функциональность |
[править] Integer#to_r
num.to_r #-> rational
Возвращает число num в виде рациональной дроби.
35.to_r #-> Rational(35, 1)
[править] Integer#truncate
int.to_i #-> int int.to_int #-> int int.floor #-> int int.ceil #-> int int.round #-> int int.truncate #-> int
В виду того, что int уже целое число, а данный метод производит округление к целому числу, то он просто возвращает значение int.
|
Полезно посмотреть на методы ceil, to_i, to_int, floor, round и truncate, которые имеют схожую функциональность |
[править] Integer#upto
int.upto(limit) {|i| block } #-> int
Выполняет блок для всех целых чисел с int по limit, включительно.
5.upto(10) { |i| print i, " " }
результат:
5 6 7 8 9 10
[править] Примесь Kernel
Since Ruby is very dynamic, methods added to the ancestors of BlankSlate after BlankSlate is defined will show up in the list of available BlankSlate methods. We handle this by defining a hook in the Object and Kernel classes that will hide any defined
Some objects are dupable, some are not. So we define a version of dup (called rake_dup) that returns self on the handful of classes that are not dupable.
Create a global fork method
Методы объекта
Array, Float, Integer, Pathname, String, URI, `, abort, at_exit, autoload?, autoload, binding, block_given?, callcc, caller, catch, chomp!, chomp, chop!, chop, eval, exec, exit!, exit, fail, fork, format, gem, getc, gets, global_variables, gsub!, gsub, iterator?, lambda, load, local_variables, loop, method_missing, open_uri_original_open, open, pp, pretty_inspect, printf, print, proc, putc, puts, p, raise, rake_dup, rand, readlines, readline, require_gem, require, scanf, scan, select, set_trace_func, sleep, split, sprintf, srand, sub!, sub, syscall, system, test, throw, to_ptr, trace_var, trap, untrace_var, warn, y
[править] Kernel#Array
Array(arg) => array
Returns arg as an Array. First tries to call arg.to_ary, then arg.to_a. If both fail, creates a single element array containing arg (unless arg is nil).
Array(1..5) #=> [1, 2, 3, 4, 5]
[править] Kernel#Float
Float(arg) => float
Returns arg converted to a float. Numeric types are converted directly, the rest are converted using arg.to_f. As of Ruby 1.8, converting nil generates a TypeError.
Float(1) #=> 1.0
Float("123.456") #=> 123.456
[править] Kernel#Integer
Integer(arg) => integer
Converts arg to a Fixnum or Bignum. Numeric types are converted directly (with floating point numbers being truncated). If arg is a String, leading radix indicators (0, 0b, and 0x) are honored. Others are converted using to_int and to_i. This behavior is different from that of String#to_i.
Integer(123.999) #=> 123
Integer("0x1a") #=> 26
Integer(Time.new) #=> 1049896590
[править] Kernel#Pathname
Pathname(path)
create a pathname object. This method is available since 1.8.5.
[править] Kernel#String
String(arg) => string
Converts arg to a String by calling its to_s method.
String(self) #=> "main"
String(self.class #=> "Object"
String(123456) #=> "123456"
[править] Kernel#URI
URI(uri_str)
alias for URI.parse. This method is introduced at 1.8.2.
[править] Kernel#`
`cmd` => string
Returns the standard output of running cmd in a subshell. The built-in syntax %x{...} uses this method. Sets $? to the process status.
`date` #=> "Wed Apr 9 08:56:30 CDT 2003\n"
`ls testdir`.split[1] #=> "main.rb"
`echo oops && exit 99` #=> "oops\n"
$?.exitstatus #=> 99
[править] Kernel#abort
abort Kernel::abort Process::abort
Terminate execution immediately, effectively by calling Kernel.exit(1). If msg is given, it is written to STDERR prior to terminating.
[править] Kernel#at_exit
at_exit { block } -> proc
Converts block to a Proc object (and therefore binds it at the point of call) and registers it for execution when the program exits. If multiple handlers are registered, they are executed in reverse order of registration.
def do_at_exit(str1)
at_exit { print str1 }
end
at_exit { puts "cruel world" }
do_at_exit("goodbye ")
exit
produces:
goodbye cruel world
[править] Kernel#autoload
autoload(module, filename) => nil
Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.
autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
[править] Kernel#autoload?
autoload(module, filename) => nil
Registers filename to be loaded (using Kernel::require) the first time that module (which may be a String or a symbol) is accessed.
autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
[править] Kernel#binding
binding -> a_binding
Returns a Binding object, describing the variable and method bindings at the point of call. This object can be used when calling eval to execute the evaluated command in this environment. Also see the description of class Binding.
def getBinding(param)
return binding
end
b = getBinding("hello")
eval("param", b) #=> "hello"
[править] Kernel#block_given?
block_given? => true or false iterator? => true or false
Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.
def try
if block_given?
yield
else
"no block"
end
end
try #=> "no block"
try { "hello" } #=> "hello"
try do "hello" end #=> "hello"
[править] Kernel#callcc
callcc {|cont| block } => obj
Generates a Continuation object, which it passes to the associated block. Performing a cont.call will cause the callcc to return (as will falling through the end of the block). The value returned by the callcc is the value of the block, or the value passed to cont.call. See class Continuation for more details. Also see Kernel::throw for an alternative mechanism for unwinding a call stack.
[править] Kernel#caller
caller(start=1) => array
Returns the current execution stack---an array containing strings in the form ``file:line or ``file:line: in `method'. The optional start parameter determines the number of initial stack entries to omit from the result.
def a(skip)
caller(skip)
end
def b(skip)
a(skip)
end
def c(skip)
b(skip)
end
c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
c(2) #=> ["prog:8:in `c'", "prog:12"]
c(3) #=> ["prog:13"]
[править] Kernel#catch
catch(symbol) {| | block } > obj
catch executes its block. If a throw is executed, Ruby searches up its stack for a catch block with a tag corresponding to the throw's symbol. If found, that block is terminated, and catch returns the value given to throw. If throw is not called, the block terminates normally, and the value of catch is the value of the last expression evaluated. catch expressions may be nested, and the throw call need not be in lexical scope.
def routine(n)
puts n
throw :done if n <= 0
routine(n-1)
end
catch(:done) { routine(3) }
produces:
3
2
1
0
[править] Kernel#chomp
chomp => $_ chomp(string) => $_
Equivalent to $_ = $_.chomp(string). See String#chomp.
$_ = "now\n"
chomp #=> "now"
$_ #=> "now"
chomp "ow" #=> "n"
$_ #=> "n"
chomp "xxx" #=> "n"
$_ #=> "n"
[править] Kernel#chomp!
chomp! => $_ or nil chomp!(string) => $_ or nil
Equivalent to $_.chomp!(string). See String#chomp!
$_ = "now\n"
chomp! #=> "now"
$_ #=> "now"
chomp! "x" #=> nil
$_ #=> "now"
[править] Kernel#chop
chop => string
Equivalent to ($_.dup).chop!, except nil is never returned. See String#chop!.
a = "now\r\n"
$_ = a
chop #=> "now"
$_ #=> "now"
chop #=> "no"
chop #=> "n"
chop #=> ""
chop #=> ""
a #=> "now\r\n"
[править] Kernel#chop!
chop! => $_ or nil
Equivalent to $_.chop!.
a = "now\r\n"
$_ = a
chop! #=> "now"
chop! #=> "no"
chop! #=> "n"
chop! #=> ""
chop! #=> nil
$_ #=> ""
a #=> ""
[править] Kernel#eval
eval(string [, binding [, filename [,lineno]]]) => obj
Evaluates the Ruby expression(s) in string. If binding is given, the evaluation is performed in its context. The binding may be a Binding object or a Proc object. If the optional filename and lineno parameters are present, they will be used when reporting syntax errors.
def getBinding(str)
return binding
end
str = "hello"
eval "str + ' Fred'" #=> "hello Fred"
eval "str + ' Fred'", getBinding("bye") #=> "bye Fred"
[править] Kernel#exec
exec(command [, arg, ...])
Replaces the current process by running the given external command. If exec is given a single argument, that argument is taken as a line that is subject to shell expansion before being executed. If multiple arguments are given, the second and subsequent arguments are passed as parameters to command with no shell expansion. If the first argument is a two-element array, the first element is the command to be executed, and the second argument is used as the argv[0] value, which may show up in process listings. In MSDOS environments, the command is executed in a subshell; otherwise, one of the exec(2) system calls is used, so the running command may inherit some of the environment of the original program (including open file descriptors).
exec "echo *" # echoes list of files in current directory
# never get here
exec "echo", "*" # echoes an asterisk
# never get here
[править] Kernel#exit
exit(integer=0) Kernel::exit(integer=0) Process::exit(integer=0)
Initiates the termination of the Ruby script by raising the SystemExit exception. This exception may be caught. The optional parameter is used to return a status code to the invoking environment.
begin
exit
puts "never get here"
rescue SystemExit
puts "rescued a SystemExit exception"
end
puts "after begin block"
produces:
rescued a SystemExit exception
after begin block
Just prior to termination, Ruby executes any at_exit functions (see Kernel::at_exit) and runs any object finalizers (see ObjectSpace::define_finalizer).
at_exit { puts "at_exit function" }
ObjectSpace.define_finalizer("string", proc { puts "in finalizer" })
exit
produces:
at_exit function
in finalizer
[править] Kernel#exit!
Process.exit!(fixnum=-1)
Exits the process immediately. No exit handlers are run. fixnum is returned to the underlying system as the exit status.
Process.exit!(0)
[править] Kernel#fail
raise raise(string) raise(exception [, string [, array]]) fail fail(string) fail(exception [, string [, array]])
With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.
raise "Failed to create socket"
raise ArgumentError, "No parameters", caller
Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:
Kernel#fork, Kernel#fork===Kernel#format===
format(format_string [, arguments...] ) => string sprintf(format_string [, arguments...] ) => string
Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:
Flag | Applies to | Meaning
---------+--------------+-----------------------------------------
space | bdeEfgGiouxX | Leave a space at the start of
| | positive numbers.
---------+--------------+-----------------------------------------
(digit)$ | all | Specifies the absolute argument number
| | for this field. Absolute and relative
| | argument numbers cannot be mixed in a
| | sprintf string.
---------+--------------+-----------------------------------------
# | beEfgGoxX | Use an alternative format. For the
| | conversions `o', `x', `X', and `b',
| | prefix the result with ``0, ``0x, ``0X,
| | and ``0b, respectively. For `e',
| | `E', `f', `g', and 'G', force a decimal
| | point to be added, even if no digits follow.
| | For `g' and 'G', do not remove trailing zeros.
---------+--------------+-----------------------------------------
+ | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
---------+--------------+-----------------------------------------
- | all | Left-justify the result of this conversion.
---------+--------------+-----------------------------------------
0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
---------+--------------+-----------------------------------------
* | all | Use the next argument as the field width.
| | If negative, left-justify the result. If the
| | asterisk is followed by a number and a dollar
| | sign, use the indicated argument as the width.
The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field. For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.) The field types are:
Field | Conversion
------+--------------------------------------------------------------
b | Convert argument as a binary number.
c | Argument is the numeric code for a single character.
d | Convert argument as a decimal number.
E | Equivalent to `e', but uses an uppercase E to indicate
| the exponent.
e | Convert floating point argument into exponential notation
| with one digit before the decimal point. The precision
| determines the number of fractional digits (defaulting to six).
f | Convert floating point argument as [-]ddd.ddd,
| where the precision determines the number of digits after
| the decimal point.
G | Equivalent to `g', but use an uppercase `E' in exponent form.
g | Convert a floating point number using exponential form
| if the exponent is less than -4 or greater than or
| equal to the precision, or in d.dddd form otherwise.
i | Identical to `d'.
o | Convert argument as an octal number.
p | The valuing of argument.inspect.
s | Argument is a string to be substituted. If the format
| sequence contains a precision, at most that many characters
| will be copied.
u | Treat argument as an unsigned decimal number. Negative integers
| are displayed as a 32 bit two's complement plus one for the
| underlying architecture; that is, 2 ** 32 + n. However, since
| Ruby has no inherent limit on bits used to represent the
| integer, this value is preceded by two dots (..) in order to
| indicate a infinite number of leading sign bits.
X | Convert argument as a hexadecimal number using uppercase
| letters. Negative numbers will be displayed with two
| leading periods (representing an infinite string of
| leading 'FF's.
x | Convert argument as a hexadecimal number.
| Negative numbers will be displayed with two
| leading periods (representing an infinite string of
| leading 'ff's.
Examples:
sprintf("%d %04x", 123, 123) #=> "123 007b"
sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'"
sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello"
sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8"
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23"
sprintf("%u", -123) #=> "..4294967173"
[править] Kernel#gem
gem(gem_name, *version_requirements)
Adds a Ruby Gem to the $LOAD_PATH. Before a Gem is loaded, its required Gems are loaded. If the version information is omitted, the highest version Gem of the supplied name is loaded. If a Gem is not found that meets the version requirement and/or a required Gem is not found, a Gem::LoadError is raised. More information on version requirements can be found in the Gem::Version documentation. The gem directive should be executed before any require statements (otherwise rubygems might select a conflicting library version). You can define the environment variable GEM_SKIP as a way to not load specified gems. you might do this to test out changes that haven't been intsalled yet. Example:
GEM_SKIP=libA:libB ruby-I../libA -I../libB ./mycode.rb
[String or Gem::Dependency] The gem name or dependency instance. [default=">= 0.0.0"] The version requirement. [Boolean] true if the Gem is loaded, otherwise false.
[Gem::LoadError] if Gem cannot be found, is listed in GEM_SKIP, or version requirement not met.[править] Kernel#getc
getc()
obsolete
[править] Kernel#gets
gets(separator=$/) => string or nil
Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line. Returns nil at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If multiple filenames are present in ARGV, +gets(nil)+ will read the contents one file at a time.
ARGV << "testfile"
print while gets
produces:
This is line one
This is line two
This is line three
And so on...
The style of programming using $_ as an implicit parameter is gradually losing favor in the Ruby community.
[править] Kernel#global_variables
global_variables => array
Returns an array of the names of global variables.
global_variables.grep /std/ #=> ["$stderr", "$stdout", "$stdin"]
[править] Kernel#gsub
gsub(pattern, replacement) => string
gsub(pattern) {|...| block } => string
Equivalent to $_.gsub..., except that $_ receives the modified result.
$_ = "quick brown fox"
gsub /[aeiou]/, '*' #=> "q**ck br*wn f*x"
$_ #=> "q**ck br*wn f*x"
[править] Kernel#gsub!
gsub!(pattern, replacement) => string or nil
gsub!(pattern) {|...| block } => string or nil
Equivalent to Kernel::gsub, except nil is returned if $_ is not modified.
$_ = "quick brown fox"
gsub! /cat/, '*' #=> nil
$_ #=> "quick brown fox"
[править] Kernel#iterator?
block_given? => true or false iterator? => true or false
Returns true if yield would execute a block in the current context. The iterator? form is mildly deprecated.
def try
if block_given?
yield
else
"no block"
end
end
try #=> "no block"
try { "hello" } #=> "hello"
try do "hello" end #=> "hello"
[править] Kernel#lambda
proc { |...| block } => a_proc
lambda { |...| block } => a_proc
Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
[править] Kernel#load
load(filename, wrap=false) => true
Loads and executes the Ruby program in the file filename. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:. If the optional wrap parameter is true, the loaded script will be executed under an anonymous module, protecting the calling program's global namespace. In no circumstance will any local variables in the loaded file be propagated to the loading environment.
[править] Kernel#local_variables
local_variables => array
Returns the names of the current local variables.
fred = 1
for i in 1..10
# ...
end
local_variables #=> ["fred", "i"]
[править] Kernel#loop
loop {|| block }
Repeatedly executes the block.
loop do
print "Input: "
line = gets
break if !line or line =~ /^qQ/
# ...
end
[править] Kernel#method_missing
obj.method_missing(symbol [, *args] ) => result
Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.
class Roman
def romanToInt(str)
# ...
end
def method_missing(methId)
str = methId.id2name
romanToInt(str)
end
end
r = Roman.new
r.iv #=> 4
r.xxiii #=> 23
r.mm #=> 2000
Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:
Kernel#open, Kernel#open_uri_original_open, Kernel#open===Kernel#open_uri_original_open===
open_uri_original_open(...)
Alias for #open
[править] Kernel#p
p(obj, ...) => nil
For each object, directly writes obj.inspect followed by the current output record separator to the program's standard output.
S = Struct.new(:name, :state)
s = S['dave', 'TX']
p s
produces:
#<S name="dave", state="TX">
[править] Kernel#pp
pp(*objs)
prints arguments in pretty form. pp returns nil.
[править] Kernel#pretty_inspect
pretty_inspect()
returns a pretty printed object as a string.
[править] Kernel#print
print(obj, ...) => nil
Prints each object in turn to $stdout. If the output field separator ($,) is not nil, its contents will appear between each field. If the output record separator ($\) is not nil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren't strings will be converted by calling their to_s method.
print "cat", [1,2,3], 99, "\n"
$, = ", "
$\ = "\n"
print "cat", [1,2,3], 99
produces:
cat12399
cat, 1, 2, 3, 99
[править] Kernel#printf
printf(io, string [, obj ... ] ) => nil printf(string [, obj ... ] ) => nil
Equivalent to:
io.write(sprintf(string, obj, ...)
or
$stdout.write(sprintf(string, obj, ...)
[править] Kernel#proc
proc { |...| block } => a_proc
lambda { |...| block } => a_proc
Equivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
[править] Kernel#putc
putc(int) => int
Equivalent to:
$stdout.putc(int)
[править] Kernel#puts
puts(obj, ...) => nil
Equivalent to
$stdout.puts(obj, ...)
[править] Kernel#raise
raise raise(string) raise(exception [, string [, array]]) fail fail(string) fail(exception [, string [, array]])
With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.
raise "Failed to create socket"
raise ArgumentError, "No parameters", caller
[править] Kernel#rake_dup
rake_dup()
Duplicate an object if it can be duplicated. If it can not be cloned or duplicated, then just return the original object.
[править] Kernel#rand
rand(max=0) => number
Converts max to an integer using max1 = max.to_i.abs. If the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0. Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max1. Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. Ruby currently uses a modified Mersenne Twister with a period of 219937-1.
srand 1234 #=> 0
[ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
[ rand(10), rand(1000) ] #=> [6, 817]
srand 1234 #=> 1234
[ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
[править] Kernel#readline
readline(separator=$/) => string
Equivalent to Kernel::gets, except readline raises EOFError at end of file.
[править] Kernel#readlines
readlines(separator=$/) => array
Returns an array containing the lines returned by calling Kernel.gets(separator) until the end of file.
[править] Kernel#require
require(string) => true or false
Ruby tries to load the library named string, returning true if successful. If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $:. If the file has the extension ``.rb, it is loaded as a source file; if the extension is ``.so, ``.o, or ``.dll, or whatever the default shared library extension is on the current platform, Ruby loads the shared library as a Ruby extension. Otherwise, Ruby tries adding ``.rb, ``.so, and so on to the name. The name of the loaded feature is added to the array in $". A feature will not be loaded if it's name already appears in $". However, the file name is not converted to an absolute path, so that ``require 'a';require './a' will load a.rb twice.
require "my-library.rb"
require "db-driver"
[править] Kernel#require_gem
require_gem(gem_name, *version_requirements)
Same as the gem command, but will also require a file if the gem provides an auto-required file name. DEPRECATED! Use gem instead.
[править] Kernel#scan
scan(pattern) => array
scan(pattern) {|///| block } => $_
Equivalent to calling $_.scan. See String#scan.
[править] Kernel#scanf
scanf(fs,&b)
(нет описания...)
[править] Kernel#select
IO.select(read_array [, write_array [, error_array [, timeout]]] ) => array or nil
See Kernel#select.
[править] Kernel#set_trace_func
set_trace_func(proc) => proc set_trace_func(nil) => nil
Establishes proc as the handler for tracing, or disables tracing if the parameter is nil. proc takes up to six parameters: an event name, a filename, a line number, an object id, a binding, and the name of a class. proc is invoked whenever an event occurs. Events are: c-call (call a C-language routine), c-return (return from a C-language routine), call (call a Ruby method), class (start a class or module definition), end (finish a class or module definition), line (execute code on a new line), raise (raise an exception), and return (return from a Ruby method). Tracing is disabled within the context of proc.
class Test
def test
a = 1
b = 2
end
end
set_trace_func proc { |event, file, line, id, binding, classname|
printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
}
t = Test.new
t.test
line prog.rb:11 false
c-call prog.rb:11 new Class
c-call prog.rb:11 initialize Object
c-return prog.rb:11 initialize Object
c-return prog.rb:11 new Class
line prog.rb:12 false
call prog.rb:2 test Test
line prog.rb:3 test Test
line prog.rb:4 test Test
return prog.rb:4 test Test
[править] Kernel#sleep
sleep([duration]) => fixnum
Suspends the current thread for duration seconds (which may be any number, including a Float with fractional seconds). Returns the actual number of seconds slept (rounded), which may be less than that asked for if another thread calls Thread#run. Zero arguments causes sleep to sleep forever.
Time.new #=> Wed Apr 09 08:56:32 CDT 2003
sleep 1.2 #=> 1
Time.new #=> Wed Apr 09 08:56:33 CDT 2003
sleep 1.9 #=> 2
Time.new #=> Wed Apr 09 08:56:35 CDT 2003
[править] Kernel#split
split([pattern [, limit]]) => array
Equivalent to $_.split(pattern, limit). See String#split.
[править] Kernel#sprintf
format(format_string [, arguments...] ) => string sprintf(format_string [, arguments...] ) => string
Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:
Flag | Applies to | Meaning
---------+--------------+-----------------------------------------
space | bdeEfgGiouxX | Leave a space at the start of
| | positive numbers.
---------+--------------+-----------------------------------------
(digit)$ | all | Specifies the absolute argument number
| | for this field. Absolute and relative
| | argument numbers cannot be mixed in a
| | sprintf string.
---------+--------------+-----------------------------------------
# | beEfgGoxX | Use an alternative format. For the
| | conversions `o', `x', `X', and `b',
| | prefix the result with ``0, ``0x, ``0X,
| | and ``0b, respectively. For `e',
| | `E', `f', `g', and 'G', force a decimal
| | point to be added, even if no digits follow.
| | For `g' and 'G', do not remove trailing zeros.
---------+--------------+-----------------------------------------
+ | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
---------+--------------+-----------------------------------------
- | all | Left-justify the result of this conversion.
---------+--------------+-----------------------------------------
0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
---------+--------------+-----------------------------------------
* | all | Use the next argument as the field width.
| | If negative, left-justify the result. If the
| | asterisk is followed by a number and a dollar
| | sign, use the indicated argument as the width.
The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field. For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.) The field types are:
Field | Conversion
------+--------------------------------------------------------------
b | Convert argument as a binary number.
c | Argument is the numeric code for a single character.
d | Convert argument as a decimal number.
E | Equivalent to `e', but uses an uppercase E to indicate
| the exponent.
e | Convert floating point argument into exponential notation
| with one digit before the decimal point. The precision
| determines the number of fractional digits (defaulting to six).
f | Convert floating point argument as [-]ddd.ddd,
| where the precision determines the number of digits after
| the decimal point.
G | Equivalent to `g', but use an uppercase `E' in exponent form.
g | Convert a floating point number using exponential form
| if the exponent is less than -4 or greater than or
| equal to the precision, or in d.dddd form otherwise.
i | Identical to `d'.
o | Convert argument as an octal number.
p | The valuing of argument.inspect.
s | Argument is a string to be substituted. If the format
| sequence contains a precision, at most that many characters
| will be copied.
u | Treat argument as an unsigned decimal number. Negative integers
| are displayed as a 32 bit two's complement plus one for the
| underlying architecture; that is, 2 ** 32 + n. However, since
| Ruby has no inherent limit on bits used to represent the
| integer, this value is preceded by two dots (..) in order to
| indicate a infinite number of leading sign bits.
X | Convert argument as a hexadecimal number using uppercase
| letters. Negative numbers will be displayed with two
| leading periods (representing an infinite string of
| leading 'FF's.
x | Convert argument as a hexadecimal number.
| Negative numbers will be displayed with two
| leading periods (representing an infinite string of
| leading 'ff's.
Examples:
sprintf("%d %04x", 123, 123) #=> "123 007b"
sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'"
sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello"
sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8"
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23"
sprintf("%u", -123) #=> "..4294967173"
[править] Kernel#srand
srand(number=0) => old_seed
Seeds the pseudorandom number generator to the value of number.to_i.abs. If number is omitted or zero, seeds the generator using a combination of the time, the process id, and a sequence number. (This is also the behavior if Kernel::rand is called without previously calling srand, but without the sequence.) By setting the seed to a known value, scripts can be made deterministic during testing. The previous seed value is returned. Also see Kernel::rand.
[править] Kernel#sub
sub(pattern, replacement) => $_
sub(pattern) { block } => $_
Equivalent to $_.sub(args), except that $_ will be updated if substitution occurs.
[править] Kernel#sub!
sub!(pattern, replacement) => $_ or nil
sub!(pattern) {|...| block } => $_ or nil
Equivalent to $_.sub!(args).
[править] Kernel#syscall
syscall(fixnum [, args...]) => integer
Calls the operating system function identified by fixnum, passing in the arguments, which must be either String objects, or Integer objects that ultimately fit within a native long. Up to nine parameters may be passed (14 on the Atari-ST). The function identified by fixnum is system dependent. On some Unix systems, the numbers may be obtained from a header file called syscall.h.
syscall 4, 1, "hello\n", 6 # '4' is write(2) on our box
produces:
hello
[править] Kernel#system
system(cmd [, arg, ...]) => true or false
Executes cmd in a subshell, returning true if the command was found and ran successfully, false otherwise. An error status is available in $?. The arguments are processed in the same way as for Kernel::exec.
system("echo *")
system("echo", "*")
produces:
config.h main.rb
*
[править] Kernel#test
test(int_cmd, file1 [, file2] ) => obj
Uses the integer aCmd to perform various tests on
file1 (first table below) or on file1 and
file2 (second table).
File tests on a single file:
Test Returns Meaning
?A | Time | Last access time for file1
?b | boolean | True if file1 is a block device
?c | boolean | True if file1 is a character device
?C | Time | Last change time for file1
?d | boolean | True if file1 exists and is a directory
?e | boolean | True if file1 exists
?f | boolean | True if file1 exists and is a regular file
?g | boolean | True if file1 has the \CF{setgid} bit
| | set (false under NT)
?G | boolean | True if file1 exists and has a group
| | ownership equal to the caller's group
?k | boolean | True if file1 exists and has the sticky bit set
?l | boolean | True if file1 exists and is a symbolic link
?M | Time | Last modification time for file1
?o | boolean | True if file1 exists and is owned by
| | the caller's effective uid
?O | boolean | True if file1 exists and is owned by
| | the caller's real uid
?p | boolean | True if file1 exists and is a fifo
?r | boolean | True if file1 is readable by the effective
| | uid/gid of the caller
?R | boolean | True if file is readable by the real
| | uid/gid of the caller
?s | int/nil | If file1 has nonzero size, return the size,
| | otherwise return nil
?S | boolean | True if file1 exists and is a socket
?u | boolean | True if file1 has the setuid bit set
?w | boolean | True if file1 exists and is writable by
| | the effective uid/gid
?W | boolean | True if file1 exists and is writable by
| | the real uid/gid
?x | boolean | True if file1 exists and is executable by
| | the effective uid/gid
?X | boolean | True if file1 exists and is executable by
| | the real uid/gid
?z | boolean | True if file1 exists and has a zero length
Tests that take two files:
?- | boolean | True if file1 and file2 are identical
?= | boolean | True if the modification times of file1
| | and file2 are equal
?< | boolean | True if the modification time of file1
| | is prior to that of file2
?> | boolean | True if the modification time of file1
| | is after that of file2
[править] Kernel#throw
throw(symbol [, obj])
Transfers control to the end of the active catch block waiting for symbol. Raises NameError if there is no catch block for the symbol. The optional second parameter supplies a return value for the catch block, which otherwise defaults to nil. For examples, see Kernel::catch.
[править] Kernel#to_ptr
to_ptr()
Allows arbitrary objects to be passed as a pointer to functions. (Probably not very GC safe, but by encapsulating it like this we can change the implementation later.)
[править] Kernel#trace_var
trace_var(symbol, cmd ) => nil
trace_var(symbol) {|val| block } => nil
Controls tracing of assignments to global variables. The parameter +symbol_ identifies the variable (as either a string name or a symbol identifier). cmd (which may be a string or a Proc object) or block is executed whenever the variable is assigned. The block or Proc object receives the variable's new value as a parameter. Also see Kernel::untrace_var.
trace_var :$_, proc {|v| puts "$_ is now '#{v}'" }
$_ = "hello"
$_ = ' there'
produces:
$_ is now 'hello'
$_ is now ' there'
[править] Kernel#trap
Signal.trap( signal, proc ) => obj
Signal.trap( signal ) {| | block } => obj
Specifies the handling of signals. The first parameter is a signal name (a string such as ``SIGALRM, ``SIGUSR1, and so on) or a signal number. The characters ``SIG may be omitted from the signal name. The command or block specifies code to be run when the signal is raised. If the command is the string ``IGNORE or ``SIG_IGN, the signal will be ignored. If the command is ``DEFAULT or ``SIG_DFL, the operating system's default handler will be invoked. If the command is ``EXIT, the script will be terminated by the signal. Otherwise, the given command or block will be run. The special signal name ``EXIT or signal number zero will be invoked just prior to program termination. trap returns the previous handler for the given signal.
Signal.trap(0, proc { puts "Terminating: #{$$}" })
Signal.trap("CLD") { puts "Child died" }
fork && Process.wait
produces:
Terminating: 27461
Child died
Terminating: 27460
[править] Kernel#untrace_var
untrace_var(symbol [, cmd] ) => array or nil
Removes tracing for the specified command on the given global variable and returns nil. If no command is specified, removes all tracing for that variable and returns an array containing the commands actually removed.
[править] Kernel#warn
warn(msg)
(нет описания...)
[править] Kernel#y
y( object, *objects )
Prints any supplied objects out in YAML. Intended as a variation on +Kernel::p+.
S = Struct.new(:name, :state)
s = S['dave', 'TX']
y s
_produces:_
--- !ruby/struct:S
name: dave
state: TX
[править] Примесь Math
Примесь Math содержит методы вычисления простейших тригонометрических и трансцендентных функций. Смотри список констант в классе Float, чтобы определить погрешность для чисел с плавающей точкой.
Константы
E, PI
Методы класса
acosh, acos, asinh, asin, atan2, atanh, atan, cosh, cos, erfc, erf, exp, frexp, hypot, ldexp, log10, log, sinh, sin, sqrt, tanh, tan
[править] Math::acos
Math.acos(x) #-> float
Вычисляет арккосинус числа x. Возвращает значения в диапазоне 0..PI.
[править] Math::acosh
Math.acosh(x) #-> float
Вычисляет значение обратной функции для гиперболического косинуса числа x.
[править] Math::asin
Math.asin(x) #-> float
Вычисляет арксинус числа x. Возвращает значения в диапазоне 0..PI.
[править] Math::asinh
Math.asinh(x) #-> float
Вычисляет значение обратной функции для гиперболического синуса числа x.
[править] Math::atan
Math.atan(x) #-> float
Вычисляет арктангенс числа x. Возвращает значения в диапазоне -{PI/2} .. {PI/2}.
[править] Math::atan2
Math.atan2(y, x) #-> float
Вычисляет арктангенс отношения, заданного числами y и x. Возвращает значения в диапазоне -PI..PI.
[править] Math::atanh
Math.atanh(x) #-> float
Вычисляет значение обратной функции гиперболического тангенса числа x.
[править] Math::cos
Math.cos(x) #-> float
Вычисляет косинус угла x (заданного в радианах). Возвращает значения в диапазоне -1..1.
[править] Math::cosh
Math.cosh(x) #-> float
Вычисляет гиперболический косинус угла x (заданного в радианах).
[править] Math::erf
Math.erf(x) #-> float
Вычисляет функцию ошибок x.
[править] Math::erfc
Math.erfc(x) #-> float
Вычисляет дополнительную функцию ошибок x.
[править] Math::exp
Math.exp(x) #-> float
Возвращает e**x (экспоненту числа х).
[править] Math::frexp
Math.frexp(numeric) #-> [ fraction, exponent ]
Представляет число numeric в виде приведенного дробного числа (типа Float) и экспоненты (типа Fixnum). Возвращает массив из двух элементов, где первый элемент — дробное число, а второй — экспонента.
fraction, exponent = Math.frexp(1234) #-> [0.6025390625, 11] fraction * 2**exponent #-> 1234.0
[править] Math::hypot
Math.hypot(x, y) #-> float
Возвращает sqrt(x**2 + y**2), то есть гипотенузу прямоугольного треугольника с катетами x и y.
Math.hypot(3, 4) #-> 5.0
[править] Math::ldexp
Math.ldexp(flt, int) #-> float
Возвращает результат выражения flt*(2**int).
fraction, exponent = Math.frexp(1234) Math.ldexp(fraction, exponent) #-> 1234.0
[править] Math::log
Math.log(numeric) #-> float
Возвращает натуральный логарифм числа numeric.
[править] Math::log10
Math.log10(numeric) #-> float
Возвращает десятичный логарифм числа numeric.
[править] Math::sin
Math.sin(x) #-> float
Вычисляет синус угла x (заданного в радианах). Returns -1..1.
[править] Math::sinh
Math.sinh(x) #-> float
Вычисляет гиперболический синус угла x (заданного в радианах).
[править] Math::sqrt
Math.sqrt(numeric) #-> float
Извлекает квадратный корень из неотрицательного числа numeric.
[править] Math::tan
Math.tan(x) #-> float
Вычисляет тангенс угла x (заданного в радианах).
[править] Math::tanh
Math.tanh() #-> float
Вычисляет гиперболический тангенс угла x (заданного в радианах).
[править] Класс Module
A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not. Conversely, module methods may be called without creating an encapsulating object, while instance methods may not. (See Module#module_function) In the descriptions that follow, the parameter syml refers to a symbol, which is either a quoted string or a Symbol (such as :name).
module Mod
include Math
CONST = 1
def meth
# ...
end
end
Mod.class #=> Module
Mod.constants #=> ["E", "PI", "CONST"]
Mod.instance_methods #=> ["meth"]
Extends the module object with module and instance accessors for class attributes, just like the native attr* accessors for instance attributes.
Also, modules included into Object need to be scanned and have their instance methods removed from blank slate. In theory, modules included into Kernel would have to be removed as well, but a "feature" of Ruby prevents late includes into modules from being exposed in the first place.
Методы класса
Методы объекта
<=>, <=, <, ===, ==, >=, >, alias_method, ancestors, append_features, attr_accessor, attr_reader, attr_writer, attr, autoload?, autoload, class_eval, class_variable_get, class_variable_set, class_variables, const_defined?, const_get, const_missing, const_set, constants, define_method, extend_object, extended, freeze, include?, included_modules, included, include, instance_methods, instance_method, method_added, method_defined?, method_removed, method_undefined, module_eval, module_function, name, private_class_method, private_instance_methods, private_method_defined?, private, protected_instance_methods, protected_method_defined?, protected, public_class_method, public_instance_methods, public_method_defined?, public, remove_class_variable, remove_const, remove_method, to_s, undef_method
[править] Module::constants
Module.constants => array
Returns an array of the names of all constants defined in the system. This list includes the names of all modules and classes.
p Module.constants.sort[1..5]
produces:
["ARGV", "ArgumentError", "Array", "Bignum", "Binding"]
[править] Module::nesting
Module.nesting => array
Returns the list of Modules nested at the point of call.
module M1
module M2
$a = Module.nesting
end
end
$a #=> [M1::M2, M1]
$a[0].name #=> "M1::M2"
[править] Module::new
Module.new => mod
Module.new {|mod| block } => mod
Creates a new anonymous module. If a block is given, it is passed the module object, and the block is evaluated in the context of this module using module_eval.
Fred = Module.new do
def meth1
"hello"
end
def meth2
"bye"
end
end
a = "my string"
a.extend(Fred) #=> "my string"
a.meth1 #=> "hello"
a.meth2 #=> "bye"
[править] Module#<
mod < other => true, false, or nil
Returns true if mod is a subclass of other. Returns nil if there's no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "A<B").
[править] Module#<=
mod <= other => true, false, or nil
Returns true if mod is a subclass of other or is the same as other. Returns nil if there's no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "A<B").
[править] Module#<=>
mod <=> other_mod => -1, 0, +1, or nil
Comparison---Returns -1 if mod includes other_mod, 0 if mod is the same as other_mod, and +1 if mod is included by other_mod or if mod has no relationship with other_mod. Returns nil if other_mod is not a module.
[править] Module#==
obj == other => true or false obj.equal?(other) => true or false obj.eql?(other) => true or false
Equality---At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning. Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:
1 == 1.0 #=> true
1.eql? 1.0 #=> false
[править] Module#===
mod === obj => true or false
Case Equality---Returns true if anObject is an instance of mod or one of mod's descendents. Of limited use for modules, but can be used in case statements to classify objects by class.
[править] Module#>
mod > other => true, false, or nil
Returns true if mod is an ancestor of other. Returns nil if there's no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "B>A").
[править] Module#>=
mod >= other => true, false, or nil
Returns true if mod is an ancestor of other, or the two modules are the same. Returns nil if there's no relationship between the two. (Think of the relationship in terms of the class definition: "class A<B" implies "B>A").
[править] Module#alias_method
alias_method(new_name, old_name) => self
Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden.
module Mod
alias_method :orig_exit, :exit
def exit(code=0)
puts "Exiting with code #{code}"
orig_exit(code)
end
end
include Mod
exit(99)
produces:
Exiting with code 99
[править] Module#ancestors
mod.ancestors -> array
Returns a list of modules included in mod (including mod itself).
module Mod
include Math
include Comparable
end
Mod.ancestors #=> [Mod, Comparable, Math]
Math.ancestors #=> [Math]
Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:
Module#append_features, Module#append_features===Module#attr===
attr(symbol, writable=false) => nil
Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. If the optional writable argument is true, also creates a method called name= to set the attribute.
module Mod
attr :size, true
end
is equivalent to:
module Mod
def size
@size
end
def size=(val)
@size = val
end
end
[править] Module#attr_accessor
attr_accessor(symbol, ...) => nil
Equivalent to calling ``attrsymbol, true on each symbol in turn.
module Mod
attr_accessor(:one, :two)
end
Mod.instance_methods.sort #=> ["one", "one=", "two", "two="]
[править] Module#attr_reader
attr_reader(symbol, ...) => nil
Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling ``attr:name on each name in turn.
[править] Module#attr_writer
attr_writer(symbol, ...) => nil
Creates an accessor method to allow assignment to the attribute aSymbol.id2name.
[править] Module#autoload
mod.autoload(name, filename) => nil
Registers filename to be loaded (using Kernel::require) the first time that name (which may be a String or a symbol) is accessed in the namespace of mod.
module A
end
A.autoload(:B, "b")
A::B.doit # autoloads "b"
[править] Module#autoload?
mod.autoload?(name) => String or nil
Returns filename to be loaded if name is registered as autoload in the namespace of mod.
module A
end
A.autoload(:B, "b")
A.autoload?(:B) # => "b"
[править] Module#class_eval
mod.class_eval(string [, filename [, lineno]]) => obj
mod.module_eval {|| block } => obj
Evaluates the string or block in the context of mod. This can be used to add methods to a class. module_eval returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.
class Thing
end
a = %q{def hello() "Hello there!" end}
Thing.module_eval(a)
puts Thing.new.hello()
Thing.module_eval("invalid code", "dummy", 123)
produces:
Hello there!
dummy:123:in `module_eval': undefined local variable
or method `code' for Thing:Class
[править] Module#class_variable_get
mod.class_variable_get(symbol) => obj
Returns the value of the given class variable (or throws a NameError exception). The @@ part of the variable name should be included for regular class variables
class Fred
@@foo = 99
end
def Fred.foo
class_variable_get(:@@foo) #=> 99
end
[править] Module#class_variable_set
obj.class_variable_set(symbol, obj) => obj
Sets the class variable names by symbol to object.
class Fred
@@foo = 99
def foo
@@foo
end
end
def Fred.foo
class_variable_set(:@@foo, 101) #=> 101
end
Fred.foo
Fred.new.foo #=> 101
[править] Module#class_variables
mod.class_variables => array
Returns an array of the names of class variables in mod and the ancestors of mod.
class One
@@var1 = 1
end
class Two < One
@@var2 = 2
end
One.class_variables #=> ["@@var1"]
Two.class_variables #=> ["@@var2", "@@var1"]
[править] Module#const_defined?
mod.const_defined?(sym) => true or false
Returns true if a constant with the given name is defined by mod.
Math.const_defined? "PI" #=> true
[править] Module#const_get
mod.const_get(sym) => obj
Returns the value of the named constant in mod.
Math.const_get(:PI) #=> 3.14159265358979
Более одного метода удовлетворяет вашему запросу. Вы можете уточнить ваш запрос, выбрав один из следующих методов:
Module#const_missing, Module#const_missing===Module#const_set===
mod.const_set(sym, obj) => obj
Sets the named constant to the given object, returning that object. Creates a new constant if no constant with the given name previously existed.
Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714
Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
[править] Module#constants
mod.constants => array
Returns an array of the names of the constants accessible in mod. This includes the names of constants in any included modules (example at start of section).
[править] Module#define_method
define_method(symbol, method) => new_method
define_method(symbol) { block } => proc
Defines an instance method in the receiver. The method parameter can be a Proc or Method object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval, a point that is tricky to demonstrate because define_method is private. (This is why we resort to the send hack in this example.)
class A
def fred
puts "In Fred"
end
def create_method(name, &block)
self.class.send(:define_method, name, &block)
end
define_method(:wilma) { puts "Charge it!" }
end
class B < A
define_method(:barney, instance_method(:fred))
end
a = B.new
a.barney
a.wilma
a.create_method(:betty) { p self }
a.betty
produces:
In Fred
Charge it!
#
[править] Module#extend_object
extend_object(obj) => obj
Extends the specified object by adding this module's constants and methods (which are added as singleton methods). This is the callback method used by Object#extend.
module Picky
def Picky.extend_object(o)
if String === o
puts "Can't add Picky to a String"
else
puts "Picky added to #{o.class}"
super
end
end
end
(s = Array.new).extend Picky # Call Object.extend
(s = "quick brown fox").extend Picky
produces:
Picky added to Array
Can't add Picky to a String
[править] Module#extended
extended(p1)
Not documented
[править] Module#freeze
mod.freeze
Prevents further modifications to mod.
[править] Module#include
include(module, ...) => self
Invokes Module.append_features on each parameter in turn.
[править] Module#include?
mod.include?(module) => true or false
Returns true if module is included in mod or one of mod's ancestors.
module A
end
class B
include A
end
class C < B
end
B.include?(A) #=> true
C.include?(A) #=> true
A.include?(A) #=> false
[править] Module#included
included( othermod )
Callback invoked whenever the receiver is included in another module or class. This should be used in preference to Module.append_features if your code wants to perform some action when a module is included in another.
module A
def A.included(mod)
puts "#{self} included in #{mod}"
end
end
module Enumerable
include A
end
[править] Module#included_modules
mod.included_modules -> array
Returns the list of modules included in mod.
module Mixin
end
module Outer
include Mixin
end
Mixin.included_modules #=> []
Outer.included_modules #=> [Mixin]
[править] Module#instance_method
mod.instance_method(symbol) => unbound_method
Returns an UnboundMethod representing the given instance method in mod.
class Interpreter
def do_a() print "there, "; end
def do_d() print "Hello "; end
def do_e() print "!\n"; end
def do_v() print "Dave"; end
Dispatcher = {
?a => instance_method(:do_a),
?d => instance_method(:do_d),
?e => instance_method(:do_e),
?v => instance_method(:do_v)
}
def interpret(string)
string.each_byte {|b| Dispatcher[b].bind(self).call }
end
end
interpreter = Interpreter.new
interpreter.interpret('dave')
produces:
Hello there, Dave!
[править] Module#instance_methods
mod.instance_methods(include_super=true) => array
Returns an array containing the names of public instance methods in the receiver. For a module, these are the public methods; for a class, they are the instance (not singleton) methods. With no argument, or with an argument that is false, the instance methods in mod are returned, otherwise the methods in mod and mod's superclasses are returned.
module A
def method1() end
end
class B
def method2() end
end
class C < B
def method3() end
end
A.instance_methods #=> ["method1"]
B.instance_methods(false) #=> ["method2"]
C.instance_methods(false) #=> ["method3"]
C.instance_methods(true).length #=> 43
[править] Module#method_added
method_added(p1)
Not documented
[править] Module#method_defined?
mod.method_defined?(symbol) => true or false
Returns true if the named method is defined by mod (or its included modules and, if mod is a class, its ancestors). Public and protected methods are matched.
module A
def method1() end
end
class B
def method2() end
end
class C < B
include A
def method3() end
end
A.method_defined? :method1 #=> true
C.method_defined? "method1" #=> true
C.method_defined? "method2" #=> true
C.method_defined? "method3" #=> true
C.method_defined? "method4" #=> false
[править] Module#method_removed
method_removed(p1)
Not documented
[править] Module#method_undefined
method_undefined(p1)
Not documented
[править] Module#module_eval
mod.class_eval(string [, filename [, lineno]]) => obj
mod.module_eval {|| block } => obj
Evaluates the string or block in the context of mod. This can be used to add methods to a class. module_eval returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.
class Thing
end
a = %q{def hello() "Hello there!" end}
Thing.module_eval(a)
puts Thing.new.hello()
Thing.module_eval("invalid code", "dummy", 123)
produces:
Hello there!
dummy:123:in `module_eval': undefined local variable
or method `code' for Thing:Class
[править] Module#module_function
module_function(symbol, ...) => self
Creates module functions for the named methods. These functions may be called with the module as a receiver, and also become available as instance methods to classes that mix in the module. Module functions are copies of the original, and so may be changed independently. The instance-method versions are made private. If used with no arguments, subsequently defined methods become module functions.
module Mod
def one
"This is one"
end
module_function :one
end
class Cls
include Mod
def callOne
one
end
end
Mod.one #=> "This is one"
c = Cls.new
c.callOne #=> "This is one"
module Mod
def one
"This is the new one"
end
end
Mod.one #=> "This is one"
c.callOne #=> "This is the new one"
[править] Module#name
mod.name => string
Returns the name of the module mod.
[править] Module#private
private => self private(symbol, ...) => self
With no arguments, sets the default visibility for subsequently defined methods to private. With arguments, sets the named methods to have private visibility.
module Mod
def a() end
def b() end
private
def c() end
private :a
end
Mod.private_instance_methods #=> ["a", "c"]
[править] Module#private_class_method
mod.private_class_method(symbol, ...) => mod
Makes existing class methods private. Often used to hide the default constructor new.
class SimpleSingleton # Not thread safe
private_class_method :new
def SimpleSingleton.create(*args, &block)
@me = new(*args, &block) if ! @me
@me
end
end
[править] Module#private_instance_methods
mod.private_instance_methods(include_super=true) => array
Returns a list of the private instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.
module Mod
def method1() end
private :method1
def method2() end
end
Mod.instance_methods #=> ["method2"]
Mod.private_instance_methods #=> ["method1"]
[править] Module#private_method_defined?
mod.private_method_defined?(symbol) => true or false
Returns true if the named private method is defined by _ mod_ (or its included modules and, if mod is a class, its ancestors).
module A
def method1() end
end
class B
private
def method2() end
end
class C < B
include A
def method3() end
end
A.method_defined? :method1 #=> true
C.private_method_defined? "method1" #=> false
C.private_method_defined? "method2" #=> true
C.method_defined? "method2" #=> false
[править] Module#protected
protected => self protected(symbol, ...) => self
With no arguments, sets the default visibility for subsequently defined methods to protected. With arguments, sets the named methods to have protected visibility.
[править] Module#protected_instance_methods
mod.protected_instance_methods(include_super=true) => array
Returns a list of the protected instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.
[править] Module#protected_method_defined?
mod.protected_method_defined?(symbol) => true or false
Returns true if the named protected method is defined by mod (or its included modules and, if mod is a class, its ancestors).
module A
def method1() end
end
class B
protected
def method2() end
end
class C < B
include A
def method3() end
end
A.method_defined? :method1 #=> true
C.protected_method_defined? "method1" #=> false
C.protected_method_defined? "method2" #=> true
C.method_defined? "method2" #=> true
[править] Module#public
public => self public(symbol, ...) => self
With no arguments, sets the default visibility for subsequently defined methods to public. With arguments, sets the named methods to have public visibility.
[править] Module#public_class_method
mod.public_class_method(symbol, ...) => mod
Makes a list of existing class methods public.
[править] Module#public_instance_methods
mod.public_instance_methods(include_super=true) => array
Returns a list of the public instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.
[править] Module#public_method_defined?
mod.public_method_defined?(symbol) => true or false
Returns true if the named public method is defined by mod (or its included modules and, if mod is a class, its ancestors).
module A
def method1() end
end
class B
protected
def method2() end
end
class C < B
include A
def method3() end
end
A.method_defined? :method1 #=> true
C.public_method_defined? "method1" #=> true
C.public_method_defined? "method2" #=> false
C.method_defined? "method2" #=> true
[править] Module#remove_class_variable
remove_class_variable(sym) => obj
Removes the definition of the sym, returning that constant's value.
class Dummy
@@var = 99
puts @@var
remove_class_variable(:@@var)
puts(defined? @@var)
end
produces:
99
nil
[править] Module#remove_const
remove_const(sym) => obj
Removes the definition of the given constant, returning that constant's value. Predefined classes and singleton objects (such as true) cannot be removed.
[править] Module#remove_method
remove_method(symbol) => self
Removes the method identified by symbol from the current class. For an example, see Module.undef_method.
[править] Module#to_s
mod.to_s => string
Return a string representing this module or class. For basic classes and modules, this is the name. For singletons, we show information on the thing we're attached to as well.
[править] Module#undef_method
undef_method(symbol) => self
Prevents the current class from responding to calls to the named method. Contrast this with remove_method, which deletes the method from the particular class; Ruby will still search superclasses and mixed-in modules for a possible receiver.
class Parent
def hello
puts "In parent"
end
end
class Child < Parent
def hello
puts "In child"
end
end
c = Child.new
c.hello
class Child
remove_method :hello # remove from child, still in parent
end
c.hello
class Child
undef_method :hello # prevent any calls to 'hello'
end
c.hello
produces:
In child
In parent
prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError)
[править] Класс NilClass
Глобальное значение nil является единственным экземпляром класса NilClass и означает «отсутствие значения». В логическом контексте эквивалентно false. Методы, которые хотят сказать, что им нечего вернуть — возвращают nil. Переменные, значение которым не присвоено — имеют значение nil.
Методы объекта
&, ^, inspect, nil?, to_a, to_f, to_i, to_s, ||
[править] NilClass#&
false & obj #-> false nil & obj #-> false
Логическое «И» всегда возвращает false. obj всегда вычисляется, так как является агрументом метода. В этом случае нет никакого сокращенного вычисления.
[править] NilClass#^
false ^ obj #-> true или false nil ^ obj #-> true или false
Логическое «ИЛИ НЕ». Если obj равен nil или false, возвращает false; иначе возвращает true.
[править] NilClass#inspect
nil.inspect #-> "nil"
Всегда возвращает строку "nil".
[править] NilClass#nil?
nil.nil? #-> true
Всегда возвращает true.
[править] NilClass#to_a
nil.to_a #-> []
Всегда возвращает пустой массив.
[править] NilClass#to_f
nil.to_f #-> 0.0
Всегда возвращает нуль.
[править] NilClass#to_i
nil.to_i #-> 0
Всегда возвращает нуль.
[править] NilClass#to_s
nil.to_s #-> ""
Всегда возвращает пустую строку.
[править] NilClass#|
false | obj #-> true или false nil | obj #-> true или false
Логическое «ИЛИ» возвращает false, если obj равен nil или false; true иначе.
[править] Класс Numeric
Numeric — это базовый класс для всех видов чисел (Fixnum, Float и так далее). Его методы добавляются ко всем классам, которые отвечают за числа.
Примеси
Comparable (<, <=, ==, >, >=, between?)
Методы объекта
+@, -@, <=>, abs, ceil, coerce, divmod, div, eql?, floor, integer?, modulo, nonzero?, quo, remainder, round, singleton_method_added, step, to_int, truncate, zero?
[править] Numeric#+@
+num #-> num
Унарный плюс — возвращает число num в качестве результата.
[править] Numeric#-@
-num #-> numeric
Унарный минус — возвращает число num с противоположным знаком в качестве результата.
[править] Numeric#<=>
num <=> other #-> 0 или nil
Возвращает ноль, если num равно other, в противном случае — nil.
[править] Numeric#abs
num.abs #-> num или numeric
Возвращает абсолютное значение («по модулю») числа num.
12.abs #-> 12 (-34.56).abs #-> 34.56 -34.56.abs #-> 34.56
[править] Numeric#ceil
num.ceil #-> integer
Возвращает наименьшее целое число, которое больше или равно num. Класс Numeric добивается этого конвертацией num в дробное число и вызова метода Float#ceil.
1.ceil #-> 1 1.2.ceil #-> 2 (-1.2).ceil #-> -1 (-1.0).ceil #-> -1
|
Полезно посмотреть на методы round, floor и truncate, которые имеют схожую функциональность |
[править] Numeric#coerce
num.coerce(numeric) #-> array
Если numeric такого же типа, что и num, то возвращает массив, состоящий из numeric и num. Иначе, возвращает массив с numeric и num преобразованных в дробные числа. Этот метод используется при обработке арифметических операций со смешанными типами.
1.coerce(2.5) #-> [2.5, 1.0] 1.2.coerce(3) #-> [3.0, 1.2] 1.coerce(2) #-> [2, 1]
[править] Numeric#div
num.div(numeric) #-> integer
Использует оператор / для выполнения деления числа num на число numeric, после чего конвертирует результат в целое число. В классе Numeric отсутствует оператор /; вызывается оператор, реализованный в его подклассах.
[править] Numeric#divmod
num.divmod( aNumeric ) #-> anArray
Возвращает массив, состоящий из результата целочисленного деления и остатка от деления числа num на число aNumeric. То есть, если
q, r = x.divmod(y)
тогда действительно следующее равенство
q = floor(float(x)/float(y)) x = q*y + r
Частное округляется в меньшую сторону, как показано в таблице:
| a | b | a.divmod(b) | a/b | a.modulo(b) | a.remainder(b) |
|---|---|---|---|---|---|
| 13 | 4 | [3, 1] | 3 | 1 | 1 |
| 13 | -4 | [-4, -3] | -3 | -3 | 1 |
| -13 | 4 | [-4, 3] | -4 | 3 | -1 |
| -13 | -4 | [3, -1] | 3 | -1 | -1 |
| 11.5 | 4 | [2, 3.5] | 2.875 | 3.5 | 3.5 |
| 11.5 | -4 | [-3, -0.5] | -2.875 | -0.5 | 3.5 |
| -11.5 | 4 | [-3, 0.5] | -2.875 | 0.5 | -3.5 |
| -11.5 | -4 | [2, -3.5] | 2.875 | -3.5 | -3.5 |
11.divmod(3) #-> [3, 2] 11.divmod(-3) #-> [-4, -1] 11.divmod(3.5) #-> [3, 0.5] -11.divmod(3.5) #-> [-4, 3.0] 11.5.divmod(3.5) #-> [3, 1.0]
|
Полезно посмотреть на методы modulo и remainder, которые имеют схожую функциональность |
[править] Numeric#eql?
num.eql?(numeric) #-> true или false
Возвращает true, если num и numeric одного и того же типа и имеют одинаковые значения.
1 == 1.0 #-> true 1.eql?(1.0) #-> false (1.0).eql?(1.0) #-> true
[править] Numeric#floor
num.floor #-> integer
Возвращает наибольшее целое число, которое меньше или равно num. Класс Numeric добивается этого конвертацией num в дробное число и вызова метода Float#floor.
1.floor #-> 1 (-1).floor #-> -1
|
Полезно посмотреть на методы round, ceil и truncate, которые имеют схожую функциональность |
[править] Numeric#integer?
num.integer? #-> true или false
Возвращает true, если num является целым числом.
[править] Numeric#modulo
num.modulo(numeric) #-> result
Получение остатка от деления числа num на число numeric. Эквивалентен вызову num.divmod(numeric)[1].
|
Полезно посмотреть на методы divmod и remainder, которые имеют схожую функциональность |
[править] Numeric#nonzero?
num.nonzero? #-> num или nil
Возвращает num, если num не является нулем и nil — иначе. Данный метод обычно используется совместно с оператором сравнения:
a = %w( z Bb bB bb BB a aA Aa AA A ) b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b } b #-> ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
[править] Numeric#quo
num.quo(numeric) #-> result
Эквивалентен оператору /, но переопределяется в подклассах.
[править] Numeric#remainder
num.remainder(numeric) #-> result
Если num и numeric имеют разные знаки, то возвращает разность mod-numeric; иначе, возвращает mod. Для обоих случаев mod вычисляется по формуле:
num.modulo(numeric)
|
Различия между remainder и modulo (%) можно посмотреть в таблице, которая прилагается к методу divmod |
[править] Numeric#round
num.round #-> integer
Округляет число num до ближайшего целого. Класс Numeric добивается этого конвертацией num в дробное число и вызова метода Float#round.
|
Полезно посмотреть на методы ceil, floor и truncate, которые имеют схожую функциональность |
[править] Numeric#singleton_method_added
num.singleton_method_added( new_method )
Перехватывает попытки добавления метода к объекту класса Numeric (и его наследников). Всегда вызывает ошибку типа TypeError.
[править] Numeric#step
num.step(limit, step ) {|i| block } #-> num
Выполняет блок для всех чисел с шагом step, начиная с num и заканчивая limit. Значение step может быть как положительное, так и отрицательное. Главное, чтобы значение step согласовывалось с значением limit (если step < 0, то limit должен быть меньше num). Если все аргументы метода —