Built-in Classes and Modules - Ruby Library Reference - Programming Ruby 1.9 & 2.0: The Pragmatic Programmers’ Guide (2013)

Programming Ruby 1.9 & 2.0: The Pragmatic Programmers’ Guide (2013)

Part 4. Ruby Crystallized

Chapter 27. Built-in Classes and Modules

This chapter documents the classes and modules built into the standard Ruby language. They are available to every Ruby program automatically; no require is required. This section does not contain the various predefined variables and constants; they are listed in Predefined Variables.

In the descriptions that follow, we show sample invocations for each method.

new

  • String.new(val ) → str

This description shows a class method that is called as String.new. The italic parameter indicates that a single string is passed in, and the arrow indicates that another string is returned from the method. Because this return value has a different name than that of the parameter, it represents a different object.

When we illustrate instance methods, we show a sample call with a dummy object name in italics as the receiver.

lines

  • str.lines(sep=$/ ) { |line| … } → str

The parameter to String#lines is shown to have a default value; call lines with no parameter, and the value of $/ will be used. This method is an iterator, so the call is followed by a block. String#lines returns its receiver, so the receiver’s name (str in this case) appears again after the arrow.

Some methods have optional parameters. We show these parameters between angle brackets, <xxx>. We use the notation <xxx>* to indicate zero or more occurrences of xxx, and we use <xxx>+ to indicate one or more occurrences of xxx.

index

  • str.index(string <, offset> ) → int or nil

Finally, for methods that can be called in several different forms, we list each form on a separate line.

27.1 Alphabetical Listing

Standard classes are listed alphabetically, followed by the standard modules. Within each, we list the class (or module) methods, followed by the instance methods.

ArrayBasicObjectBignumBindingClassComplexDirEncodingEnumeratorExceptionFalseClassFiberFileFile::StatFixnumFloatHashIntegerIOMatchDataMethodModuleMutexNilClassNumericObjectProcProcess::StatusRandomRangeRationalRegexpStringStructStruct::TmsSymbolThreadThreadGroupTimeTracePointTrueClassUnboundMethod

Built-in Modules

ComparableEnumerableErrnoFileTestGCGC::ProfilerKernelMarshalMathObjectSpaceProcessProcess::GIDProcess::SysProcess::UIDSignal

Class Array < Object

Relies on:

each, <=>

Arrays are ordered, integer-indexed collections of any object. Array indexes start at 0, as in C or Java. A negative index is relative to the end of the array; that is, an index of -1 indicates the last element of the array, -2 is the next-to-last element in the array, and so on.

Mixes in

Enumerable

all?, any?, chunk, collect, collect_concat, count, cycle, detect, drop, drop_while, each_cons, each_entry, each_slice, each_with_index, each_with_object, entries, find, find_all, find_index, first, flat_map, grep, group_by, include?, inject, lazy, map, max, max_by, member?, min, min_by, minmax, minmax_by, none?, one?, partition, reduce, reject, reverse_each, select, slice_before, sort, sort_by, take, take_while, to_a, zip

Array: Class methods

[ ]

  • Array[<obj>* ] → an_array

Returns a new array populated with the given objects. Equivalent to the operator form Array.[...].

Array.[]( 1, 'a', /^A/ ) # => [1, "a", /^A/]

Array[ 1, 'a', /^A/ ] # => [1, "a", /^A/]

[ 1, 'a', /^A/ ] # => [1, "a", /^A/]

new

  • Array.new →an_array
  • Array.new (size=0, obj=nil ) → an_array
  • Array.new(array ) → an_array
  • Array.new(size ) { |i| … } → an_array

Returns a new array. In the first form, the new array is empty. In the second, it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is calculated by passing the element’s index to the given block and storing the return value.

Array.new # => []

Array.new(2) # => [nil, nil]

Array.new(5, "A") # => ["A", "A", "A", "A", "A"]

# only one instance of the default object is created

a = Array.new(2, Hash.new)

a[0]['cat'] = 'feline'

a # => [{"cat"=>"feline"}, {"cat"=>"feline"}]

a[1]['cat'] = 'Felix'

a # => [{"cat"=>"Felix"}, {"cat"=>"Felix"}]

a = Array.new(2) { Hash.new } # Multiple instances

a[0]['cat'] = 'feline'

a # => [{"cat"=>"feline"}, {}]

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

squares # => [0, 1, 4, 9, 16]

copy = Array.new(squares) # initialized by copying

squares[5] = 25

squares # => [0, 1, 4, 9, 16, 25]

copy # => [0, 1, 4, 9, 16]

try_convert

  • Array.try_convert(obj ) → an_array or nil

If obj is not already an array, attempts to convert it to one by calling its to_ary method. Returns nil if no conversion could be made.

class Stooges

def to_ary

[ "Larry", "Curly", "Moe" ]

end

end

Array.try_convert(Stooges.new) # => ["Larry", "Curly", "Moe"]

Array.try_convert("Shemp") # => nil

Array: Instance methods

&

  • arr& other_arrayan_array

Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates. The rules for comparing elements are the same as for hash keys. If you need setlike behavior, see the library class .Set.

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

*

  • arr* intan_array
  • arr* stra_string

Repetition—With an argument that responds to to_str , equivalent to arr.join(str). Otherwise, returns a new array built by concatenating int copies of arr.

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

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

+

  • arr+ other_arrayan_array

Concatenation—Returns a new array built by concatenating the two arrays together to produce a third array.

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

-

  • arr- other_arrayan_array

Array Difference—Returns a new array that is a copy of the original array, removing any items that also appear in other_array. If you need setlike behavior, see the library class Set.

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

<<

  • arr<< objarr

Append—Pushes the given object on to the end of this array. This expression returns the array itself, so several appends may be chained together. See also Array#push.

[ 1, 2 ] << "c" << "d" << [ 3, 4 ] # => [1, 2, "c", "d", [3, 4]]

<=>

  • arr<=> other_array → -1, 0, +1, or nil

Comparison—Returns an integer -1, 0, or +1 if this array is less than, equal to, or greater than other_array. Successive objects in each array are compared using <=> . If any pair are not equal, then that inequality is the return value. If all pair are equal, then the longer array is considered greater. Thus, two arrays are “equal” according to Array#<=> if and only if they have the same length and the values of each corresponding element are equal. nil is returned if the argument is not comparable to arr.

[ "a", "a", "c" ] <=> [ "a", "b", "c" ] # => -1

[ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ] # => 1

[ 1, 2, 3, 4, 5, 6 ] <=> "wombat" # => nil

==

  • arr== objtrue or false

Equality—Two arrays are equal if they contain the same number of elements and if each element is equal to (according to Object#==) the corresponding element in the other array. If obj is not an array, attempt to convert it using to_ary and return obj==arr.

[ "a", "c" ] == [ "a", "c", 7 ] # => false

[ "a", "c", 7 ] == [ "a", "c", 7 ] # => true

[ "a", "c", 7 ] == [ "a", "d", "f" ] # => false

[ ]

  • arr[int] →obj or nil
  • arr[start,length] → an_array or nil
  • arr[range] →an_array or nil

Element Reference—Returns the element at index int; returns a length element subarray starting at index start; or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). Returns nil if the index of the first element selected is greater than the array size. If the start index equals the array size and a length or range parameter is given, an empty array is returned. Equivalent to Array#slice.

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"]

# special cases

a[5] # => nil

a[5, 1] # => []

a[5..10] # => []

[ ]=

  • arr[int] =objobj
  • arr[start,length] = objobj}
  • arr[range] =objobj

Element Assignment—Sets the element at index int, replaces a subarray starting at index start and continuing for length elements, or replaces a subarray specified by range. If int is greater than the size of the array, the array grows automatically. A negative int counts backward from the end of the array. Inserts elements if length is zero. If obj is an array, the form with the single index inserts that array into arr, and the forms with a length or with a range replace the given elements in arr with the array contents. An IndexError is raised if a negative index points past the beginning of the array. (Prior to Ruby 1.9, assigning nil with the second and third forms of element assignment deleted the corresponding array elements; it now assigns nil to them.) See also Array#push and Array#unshift.

a = Array.new # => []

a[4] = "4"; a # => [nil, nil, nil, nil, "4"]

a[0] = [ 1, 2, 3 ]; a # => [[1, 2, 3], nil, nil, nil, "4"]

a[0, 3] = [ 'a', 'b', 'c' ]; a # => ["a", "b", "c", nil, "4"]

a[1..2] = [ 1, 2 ]; a # => ["a", 1, 2, nil, "4"]

a[0, 2] = "?"; a # => ["?", 2, nil, "4"]

a[0..2] = "A", "B", "C"; a # => ["A", "B", "C", "4"]

a[-1] = "Z"; a # => ["A", "B", "C", "Z"]

a[1..-1] = nil; a # => ["A", nil]

|

  • arr| other_arrayan_array

Set Union—Returns a new array by joining this array with other_array, removing duplicates. The rules for comparing elements are the same as for hash keys. If you need setlike behavior, see the library class Set.

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

assoc

  • arr.assoc(obj ) → an_array or nil

Searches through an array whose elements are also arrays comparing obj with the first element of each contained array using obj.==. Returns the first contained array that matches (that is, the first associated array) or nil if no match is found. See also Array#rassoc.

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

at

  • arr.at(int ) → obj or nil

Returns the element at index int. A negative index counts from the end of arr. Returns nil if the index is out of range. See also Array#[].

a = [ "a", "b", "c", "d", "e" ]

a.at(0) # => "a"

a.at(-1) # => "e"

bsearch

  • arr.bsearch { |val| … } →obj or nil

Assuming arr is sorted in ascending order, performs a binary search in O(log n) time. The method operates in two modes depending on the values returned by the block:«2.0»

To find the minimum value in arr greater than or equal to the required value, have the block return false if its argument is less than that value, true otherwise.

arr = %w{ ant bee cat dog elk fox gnu }

arr.bsearch {|val| val >= "c" } # => "cat"

arr.bsearch {|val| val >= "cod" } # => "dog"

arr.bsearch {|val| val >= "kea" } # => nil

To find a value in the array that lies between two limits, write the block to return a positive number if the argument is less than the lower bound, a negative number if it is greater than the upper bound, or zero if it is inclusively between the bounds.

arr = [ 1, 1, 2, 3, 5, 8, 13, 21, 34 ]

res = arr.bsearch do |val|

case

when val < 19 then +1

when val > 23 then -1

else 0

end

end

res # => 21

combination

  • arr.combination(size ) → enumerator
  • arr.combination(size ) { |array| … } → arr

Constructs all combinations of the elements of arr of length size. If called with a block, passes each combination to that block; otherwise, returns an enumerator object. An empty result is generated if no combinations of the given length exist. See also Array#permutation.

a = [ "a", "b", "c" ]

a.combination(1).to_a # => [["a"], ["b"], ["c"]]

a.combination(2).to_a # => [["a", "b"], ["a", "c"], ["b", "c"]]

a.combination(3).to_a # => [["a", "b", "c"]]

a.combination(4).to_a # => []

collect!

  • arr.collect! { |obj| … } →arr

Invokes block once for each element of arr, replacing the element with the value returned by block. See also Enumerable#collect.

a = [ "a", "b", "c", "d" ]

a.collect! {|x| x + "!" } # => ["a!", "b!", "c!", "d!"]

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

compact

  • arr.compact →an_array

Returns a copy of arr with all nil elements removed.

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

compact!

  • arr.compact! →arr or nil

Removes nil elements from arr. Returns nil if no changes were made.

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

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

concat

  • arr.concat(other_array ) → arr

Appends the elements in other_array to arr.

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

count

  • arr.count(obj ) → int
  • arr.count { |obj| … } →int

Returns the count of objects in arr that equal obj or for which the block returns a true value. Shadows the corresponding method in Enumerable.

[1, 2, 3, 4].count(3) # => 1

[1, 2, 3, 4].count {|obj| obj > 2 } # => 2

cycle

  • arr.cycle { |obj| … } → nil orenumerator
  • arr.cycle(times ) { |obj| … } → nil or enumerator

Returns nil if arr has no elements; otherwise, passes the elements, one at a time to the block. When it reaches the end, it repeats. The number of times it repeats is set by the parameter. If the parameter is missing, cycles forever. Returns an Enumerator object if no block is given.

[1,2,3].cycle(3) # => #<Enumerator: [1, 2, 3]:cycle(3)>

[1,2,3].cycle(3).to_a # => [1, 2, 3, 1, 2, 3, 1, 2, 3]

columns = [ 1, 2, 3 ]

data = %w{ a b c d e f g h }

columns.cycle do |column_number|

print column_number, ":", data.shift, "\t"

puts if column_number == columns.last

breakif data.empty?

end

Produces:

1:a 2:b 3:c

1:d 2:e 3:f

1:g 2:h

delete

  • arr.delete(obj ) → obj or nil
  • arr.delete(obj ) { … } → obj or nil

Deletes items from arr that are equal to obj. If the item is not found, returns nil. If the optional code block is given, returns the result of block if the item is not found.

a = [ "a", "b", "b", "b", "c" ]

a.delete("b") # => "b"

a # => ["a", "c"]

a.delete("z") # => nil

a.delete("z") { "not found" } # => "not found"

delete_at

  • arr.delete_at(index ) → obj or nil

Deletes the element at the specified index, returning that element or nil if the index is out of range. See also Array#slice!.

a = %w( ant bat cat dog )

a.delete_at(2) # => "cat"

a # => ["ant", "bat", "dog"]

a.delete_at(99) # => nil

delete_if

  • arr.delete_if { |item| … } →arr

Deletes every element of arr for which block evaluates to true.

a = [ "a", "b", "c" ]

a.delete_if {|x| x >= "b" } # => ["a"]

each

  • arr.each { |item| … } →arr

Calls block once for each element in arr, passing that element as a parameter.

a = [ "a", "b", "c" ]

a.each {|x| print x, " -- " }

Produces:

a -- b -- c --

each_index

  • arr.each_index { |index| … } →arr

Same as Array#each but passes the index of the element instead of the element itself.

a = [ "a", "b", "c" ]

a.each_index {|x| print x, " -- " }

Produces:

0 -- 1 -- 2 --

empty?

  • arr.empty? → true or false

Returns true if arr array contains no elements.

[].empty? # => true

[ 1, 2, 3 ].empty? # => false

eql?

  • arr.eql?(other ) → true or false

Returns true if arr and other are the same object or if other is an object of class Array with the same length and content as arr. Elements in the arrays are compared using Object#eql?. See also Array#<=>.

[ "a", "b", "c" ].eql?(["a", "b", "c"]) # => true

[ "a", "b", "c" ].eql?(["a", "b"]) # => false

[ "a", "b", "c" ].eql?(["b", "c", "d"]) # => false

fetch

  • arr.fetch(index ) → obj
  • arr.fetch(index, default ) → obj
  • arr.fetch(index ) { |i| … } → obj

Tries to return the element at position index. If the index lies outside the array, the first form throws an IndexError exception, the second form returns default, and the third form returns the value of invoking the block, passing in the index. Negative values of index count from the end of the array.

a = [ 11, 22, 33, 44 ]

a.fetch(1) # => 22

a.fetch(-1) # => 44

a.fetch(-1, 'cat') # => 44

a.fetch(4, 'cat') # => "cat"

a.fetch(4) {|i| i*i } # => 16

fill

  • arr.fill(obj ) → arr
  • arr.fill(obj, start <, length> ) → arr
  • arr.fill(obj, range ) → arr
  • arr.fill { |i| … } →arr
  • arr.fill(start <, length> ) { |i| … } → arr
  • arr.fill(range ) { |i| … } → arr

The first three forms set the selected elements of arr (which may be the entire array) to obj. A start of nil is equivalent to zero. A length of nil is equivalent to arr. length . The last three forms fill the array with the value of the block. The block is passed the absolute index of each element to be filled.

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(-3) {|i| i+100} # => [0, 101, 102, 103]

find_index

  • arr.find_index(obj ) → int or nil
  • arr.find_index { |item| … } →int or nil
  • arr.find_index →enumerator

Returns the index of the first object in arr that is == to obj or for which the block returns a true value. Returns nil if no match is found. See also Enumerable#select and Array#rindex.

a = [ "a", "b", "c", "b" ]

a.find_index("b") # => 1

a.find_index("z") # => nil

a.find_index {|item| item > "a"} # => 1

flatten

  • arr.flatten(level = -1 ) → an_array

Returns a new array that is a flattening of this array (recursively). That is, for every element that is an array, extracts its elements into the new array. The level parameter controls how deeply the flattening occurs. If less than zero, all subarrays are expanded. If zero, no flattening takes place. If greater than zero, only that depth of subarray is expanded.

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(0) # => [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]

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

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

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

flatten!

  • arr.flatten!(level = -1 ) → arr or nil

Same as Array#flatten but modifies the receiver in place. Returns nil if no modifications were made (i.e., arr contains no subarrays).

a = [ 1, 2, [3, [4, 5] ] ]

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

a.flatten! # => nil

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

frozen?

  • arr.frozen? → true or false

Returns true if arr is frozen or if it is in the middle of being sorted.

Table 14. Template characters for Array.pack

Directive

Meaning

@

Move to absolute position

A

Sequence of bytes (space padded, count is width)

a

Sequence of bytes (null padded, count is width)

B

Bit string (most significant first)

b

Bit string (least significant first)

C

Unsigned byte

c

Byte

D, d

Double-precision float, native format

E

Double-precision float, little-endian byte order

e

Single-precision float, little-endian byte order

F, f

Single-precision float, native format

G

Double-precision float, network (big-endian) byte order

g

Single-precision float, network (big-endian) byte order

H

Hex string (high nibble first)

h

Hex string (low nibble first)

I

Unsigned integer

i

Integer

L

Unsigned long

l

Long

M

Quoted printable, MIME encoding (see RFC2045)

m

Base64-encoded string; by default adds linefeeds every 60 characters; "m0" suppresses linefeeds

N

Long, network (big-endian) byte order

n

Short, network (big-endian) byte order

P

Pointer to a structure (fixed-length string)

p

Pointer to a null-terminated string

Q, q

64-bit number

S

Unsigned short

s

Short

U

UTF-8

u

UU-encoded string

V

Long, little-endian byte order

v

Short, little-endian byte order

w

BER-compressed integer°

X

Back up a byte

x

Null byte

Z

Same as “a,” except a null byte is appended if the * modifier is given

° The octets of a BER-compressed integer represent an unsigned integer in base 128, most significant digit first, with as few digits as possible. Bit eight (the high bit) is set on each byte except the last (Self-Describing Binary Data Representation, MacLeod).

index

  • arr.index(obj ) → int or nil
  • arr.index { |item| … } →int or nil

Synonym for Array#find_index.

insert

  • arr.insert(index, <obj>+} ) → arr

If index is not negative, inserts the given values before the element with the given index. If index is negative, adds the values after the element with the given index (counting from the end).

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"]

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

join

  • arr.join(separator=$, ) → str

Returns a string created by converting each element of the array to a string and concatenating them, separated each by separator.

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

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

keep_if

  • arr.keep_if { |obj| … } →array or enumerator

Modifies arr by removing all elements for which block is false (see also Enumerable#select and Array.select!). Returns an Enumerator object if no block is given.

a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

a.keep_if {|element| element < 6 } # => [1, 2, 3, 4, 5]

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

a.keep_if(&:odd?) # => [1, 3, 5]

a # => [1, 3, 5]

last

  • arr.last →obj or nil
  • arr.last(count ) → an_array

Returns the last element, or last count elements, of arr. If the array is empty, the first form returns nil, and the second returns an empty array. ( first is defined by Enumerable.)

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

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

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

length

  • arr.length →int

Returns the number of elements in arr.

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

map!

  • arr.map! { |obj| … } →arr

Synonym for Array#collect!.

pack

  • arr.pack (template ) → binary_string

Packs the contents of arr into a binary sequence according to the directives in template (see Table 14, Template characters for Array.pack). Directives A, a, and Z may be followed by a count, which gives the width of the resulting field. The remaining directives also may take a count, indicating the number of array elements to convert. If the count is an asterisk (*), all remaining array elements will be converted. The directives s S i I l L may be followed by an underscore (_) or bang (!) to use the underlying platform’s native size for the specified type; otherwise, they use a platform-independent size. The directives s S i I l L q Q may be followed by a less than sign to signify little endian or greater than sign for big endian. Spaces are ignored in the template string. Comments starting with # to the next newline or end of string are also ignored. See also String#unpack.

a = [ "a", "b", "c" ]

n = [ 65, 66, 67 ]

a.pack("A3A3A3") # => "a␣␣b␣␣c␣␣"

a.pack("a3a3a3") # => "a\0\0b\0\0c\0\0"

n.pack("ccc") # => "ABC"

permutation

  • arr.permutation(size=arr.size ) → enumerator
  • arr.permutation(size=arr.size ) { |array| … } → arr}

Constructs all permutations of the elements of arr of length size. If called with a block, passes each permutation to that block; otherwise, returns an enumerator object. An empty result is generated if no permutations of the given length exist. See also Array#combination.

words = {}

File.readlines("/usr/share/dict/words").map(&:chomp).each do |word|

words[word.downcase] = 1

end

%w{ c a m e l }.permutation do |letters|

anagram = letters.join

puts anagram if words[anagram]

end

Produces:

camel

clame

cleam

macle

pop

  • arr.pop(<n>* ) → obj or nil

Removes the last element (or the last n elements) from arr. Returns whatever is removed or nil if the array is empty.

a = %w{ f r a b j o u s }

a.pop # => "s"

a # => ["f", "r", "a", "b", "j", "o", "u"]

a.pop(3) # => ["j", "o", "u"]

a # => ["f", "r", "a", "b"]

product

  • arr.product(<arrays>* ) → result_array
  • arr.product(<arrays>* ) <combination> → arr

Generates all combinations of selecting an element each from arr and from any arrays passed as arguments. The number of elements in the result is the product of the lengths of arr and the lengths of the arguments (so if any of these arrays is empty, the result will be an empty array). Each element in the result is an array containing n+1 elements, where n is the number of arguments. If a block is present, it will be passed each combination, and arr will be returned.

suits = %w{ C D H S }

ranks = [ *2..10, *%w{ J Q K A } ]

card_deck = suits.product(ranks).shuffle

card_deck.first(13) # => [["S", 8], ["D", "K"], ["C", 9], ["S", "A"], ["H", "K"],

# .. ["S", 4], ["S", 7], ["D", 2], ["H", 6], ["S", "Q"],

# .. ["D", 3], ["D", 4], ["H", 10]]

push

  • arr.push(<obj>* ) → arr

Appends the given argument(s) to arr.

a = [ "a", "b", "c" ]

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

rassoc

  • arr.rassoc(key ) → an_array or nil

Searches through the array whose elements are also arrays. Compares key with the second element of each contained array using ==. Returns the first contained array that matches. See also Array#assoc.

a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]

a.rassoc("two") # => [2, "two"]

a.rassoc("four") # => nil

reject!

  • arr.reject! { |item| … } →arr or nil

Equivalent to Array#delete_if but returns nil if arr is unchanged. Also see Enumerable#reject.

repeated_combination

  • arr.repeated_combination(length ) { |comb| … } → arr
  • arr.repeated_combination(length ) → enum

Creates the set of combinations of length length of the elements of arr. If length is greater than arr.size, elements will be allowed to repeat. Passes each combination to the block, or returns an enumerator if no block is given.

a = [1, 2, 3]

a.repeated_combination(2).to_a # => [[1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3,

# .. 3]]

a.repeated_combination(3).to_a # => [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 2],

# .. [1, 2, 3], [1, 3, 3], [2, 2, 2], [2, 2, 3],

# .. [2, 3, 3], [3, 3, 3]]

repeated_permutation

  • arr.repeated_permutation(length ) { |comb| … } → arr
  • arr.repeated_permutation(length ) → enum

Creates the set of permutations of length length of the elements of arr. If length is greater than arr.size elements will be allowed to repeat. Passes each permutation to the block, or returns an enumerator if no block given.

a = [:a, :b]

a.repeated_permutation(2).to_a # => [[:a, :a], [:a, :b], [:b, :a], [:b, :b]]

a.repeated_permutation(3).to_a # => [[:a, :a, :a], [:a, :a, :b], [:a, :b, :a],

# .. [:a, :b, :b], [:b, :a, :a], [:b, :a, :b],

# .. [:b, :b, :a], [:b, :b, :b]]

replace

  • arr.replace(other_array ) → arr

Replaces the contents of arr with the contents of other_array, truncating or expanding arr if necessary.

a = [ "a", "b", "c", "d", "e" ]

a.replace([ "x", "y", "z" ]) # => ["x", "y", "z"]

a # => ["x", "y", "z"]

reverse

  • arr.reverse →an_array

Returns a new array using arr’s elements in reverse order.

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

[ 1 ].reverse # => [1]

reverse!

  • arr.reverse! →arr

Reverses arr in place.

a = [ "a", "b", "c" ]

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

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

[ 1 ].reverse! # => [1]

reverse_each

  • arr.reverse_each<item>} } → arr

Same as Array#each but traverses arr in reverse order.

a = [ "a", "b", "c" ]

a.reverse_each {|x| print x, " " }

Produces:

c b a

rindex

  • arr.rindex(obj ) → int or nil
  • arr.rindex { |item| … } →int or nil

Returns the index of the last object in arr that is == to obj or for which the block returns a true value. Returns nil if no match is found. See also Enumerable#select and Array#index.

a = [ "a", "b", "e", "b", "d" ]

a.rindex("b") # => 3

a.rindex("z") # => nil

a.rindex {|item| item =~ /[aeiou]/} # => 2

rotate

  • arr.rotate(places=1 ) → new_array

Returns a new array containing the elements of arr rotated places positions (so that the element that originally was at arr[places] is now at the front of the array. places may be negative.

a = [1, 2, 3, 4, 5]

a.rotate(2) # => [3, 4, 5, 1, 2]

a.rotate(-2) # => [4, 5, 1, 2, 3]

rotate!

  • arr.rotate(places=1 ) → arr

Rotate arr in place.

sample

  • arr.sample(n=1 ) → an_array or nil

Returns min(n, arr.size) random elements from arr or nil if arr is empty and n is not given.

a = [ "a", "b", "c", "d" ]

a.sample # => "c"

a.sample(3) # => ["b", "a", "c"]

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

b = []

b.sample # => nil

select!

  • arr.select! { |obj| … } →array, nil, or enumerator

Modifies arr by removing all elements for which block is false (see also Enumerable#select and Array#keep_if). Returns nil if no changes were made, returns an Enumerator object if no block is given, or returns arr.

a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

a.select! {|element| element < 6 } # => [1, 2, 3, 4, 5]

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

a.select! {|element| element < 8 } # => nil

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

shift

  • arr.shift( n = 1 ) →obj or nil

Returns the first n elements (or the first element with no argument) of arr and removes it (shifting all other elements down by one). Returns nil if the array is empty.

args = [ "-m", "-q", "-v", "filename" ]

args.shift # => "-m"

args.shift(2) # => ["-q", "-v"]

args # => ["filename"]

shuffle

  • arr.shuffle →an_array
  • arr.shuffle(random:rng) → an_array

Returns an array containing the elements of arr in random order. You can pass it a random number generator using the random: keyword parameter. Passing rngs with the same seed makes the shuffle deterministic.«2.0»

[ 1, 2, 3, 4, 5 ].shuffle # => [4, 5, 2, 1, 3]

[ 1, 2, 3, 4, 5 ].shuffle # => [5, 2, 1, 4, 3]

[ 1, 2, 3, 4, 5 ].shuffle(random: Random.new(123)) # => [2, 4, 5, 1, 3]

[ 1, 2, 3, 4, 5 ].shuffle(random: Random.new(123)) # => [2, 4, 5, 1, 3]

shuffle!

  • arr.shuffle! →an_array
  • arr.shuffle!(random:rng) → an_array

Randomizes the order of the elements of arr in place.

size

  • arr.size →int

Synonym for Array#length.

slice

  • arr.slice(int ) → obj
  • arr.slice(start, length ) → an_array
  • arr.slice(range ) → an_array

Synonym for Array#[ ].

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"]

# special cases

a.slice(5) # => nil

a.slice(5, 1) # => []

a.slice(5..10) # => []

slice!

  • arr.slice!(int ) → obj or nil
  • arr.slice!(start, length ) → an_array or nil
  • arr.slice!(range ) → an_array or nil

Deletes the element(s) given by an index (optionally with a length) or by a range. Returns the deleted object, subarray, or nil if the index is out of range.

a = [ "a", "b", "c" ]

a.slice!(1) # => "b"

a # => ["a", "c"]

a.slice!(-1) # => "c"

a # => ["a"]

a.slice!(100) # => nil

a # => ["a"]

sort!

  • arr.sort! →arr
  • arr.sort! { |a,b| … } →arr

Sorts arr in place (see Enumerable#sort). arr is effectively frozen while a sort is in progress.

a = [ "d", "a", "e", "c", "b" ]

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

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

sort_by!

  • arr.sort_by! { |a| … } →arr
  • arr.sort_by! →enum

Sorts arr in place (see Enumerable#sort_by). arr is effectively frozen while a sort is in progress.

a = [ 5, 2, 7, 4, 8, 9 ]

# Sort even numbers before odd, and then by rank

a.sort_by! {|e| [ e & 1, e ] } # => [2, 4, 8, 5, 7, 9]

a # => [2, 4, 8, 5, 7, 9]

to_a

  • arr.to_a →arr
  • array_subclass.to_a →array

If arr is an array, returns arr. If arr is a subclass of Array, invokes to_ary and uses the result to create a new array object.

to_ary

  • arr.to_ary →arr

Returns arr.

to_s

  • arr.to_s →str

Returns a string representation of arr. (In Ruby 1.9, the array as a literal.)

[ 1, 3, 5, 7, 9 ].to_s # => "[1, 3, 5, 7, 9]"

transpose

  • arr.transpose →an_array

Assumes that arr is an array of arrays and transposes the rows and columns.

a = [[1,2], [3,4], [5,6]]

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

uniq

  • arr.uniq<element> → an_array

Returns a new array by removing duplicate values in arr, where duplicates are detected by comparing using eql? and hash . If the block is present, the comparisons are made based on the values returned by that block for each element in the array.

a = %w{ C a a b b A c a }

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

a.uniq {|element| element.downcase } # => ["C", "a", "b"]

a.uniq(&:upcase) # => ["C", "a", "b"]

uniq!

  • arr.uniq!<element> → arr or nil

Same as Array#uniq but modifies the receiver in place. Returns nil if no changes are made (that is, no duplicates are found).

a = [ "a", "a", "b", "b", "c" ]

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

b = [ "a", "b", "c" ]

b.uniq! # => nil

unshift

  • arr.unshift(<obj>+} ) → arr

Prepends object(s) to arr.

a = [ "b", "c", "d" ]

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

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

values_at

  • arr.values_at(<selector>* ) → an_array

Returns an array containing the elements in arr corresponding to the given selector(s). The selectors may be either integer indices or ranges. Returns nil for selectors beyond the bounds of the array.«2.0»

a = %w{ a b c d e f }

a.values_at(1, 3, 5) # => ["b", "d", "f"]

a.values_at(1, 3, 5, 7) # => ["b", "d", "f", nil]

a.values_at(-1, -3, -5, -7) # => ["f", "d", "b", nil]

a.values_at(1..3, 2...5) # => ["b", "c", "d", "c", "d", "e"]

a.values_at(5..7, 1..2) # => ["f", nil, nil, "b", "c"]

Class BasicObject

BasicObject is the root of Ruby’s class hierarchy. It deliberately has just a few methods, allowing it to be conveniently used as the basis for a number of metaprogramming techniques.

If you write code in a direct descendent of BasicObject, you will not have unqualified access to the methods in Kernel, which normally get mixed in to Object. This example illustrates how to invoke Kernel methods explicitly:

class SimpleBuilder < BasicObject

def __puts_at_indent__(string)

::Kernel.puts " " * @indent + string

end

def method_missing(name, *args, &block)

@indent ||= 0

__puts_at_indent__("<#{name}>")

@indent += 2

__puts_at_indent__(args.join) unless args.empty?

yieldif ::Kernel.block_given?

@indent -= 2

__puts_at_indent__("</#{name}>")

end

end

r = SimpleBuilder.new

r.person do

r.name "Dave"

r.address do

r.street "123 Main"

r.city "Pleasantville"

end

end

Produces:

<person>

<name>

Dave

</name>

<address>

<street>

123 Main

</street>

<city>

Pleasantville

</city>

</address>

</person>

BasicObject: Instance methods

!

  • !objtrue or false

Returns false unless obj is false. Because it’s in BasicObject, ! is defined for all objects in Ruby.

==

  • obj== other_objtrue or false

Equality—At the BasicObject level, == returns true only if obj and other_obj are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.

!=

  • obj!= othertrue or false

Returns the opposite of BasicObject#==.

__id__

  • obj.__id__ →fixnum

Synonym for Object#object_id. Prior to Ruby 1.9.3, this was an instance method of class Object.

equal?

  • obj.equal?(other_obj ) → true or false

Alias for BasicObject#==.

instance_eval

  • obj.instance_eval(string <, file line> ) → other_obj
  • obj.instance_eval { |obj| … } →other_obj}

Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). To set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.

class Klass

def initialize

@secret = 99

end

end

k = Klass.new

k.instance_eval { @secret } # => 99

When metaprogramming, instance_eval is often used to execute the methods in a block in the context of the caller:

class Recorder < BasicObject

attr_reader :__calls__

def method_missing(name, *args, &block)

@__calls__ ||= []

@__calls__ << [ name, args ]

end

def record(&block)

instance_eval(&block)

end

end

r = Recorder.new

r.record do

disable "safety"

pull "control rod", dir: "out"

run

end

p r.__calls__

Produces:

[[:disable, ["safety"]], [:pull, ["control rod", {:dir=>"out"}]], [:run, []]]

instance_exec

  • obj.instance_exec(<args>*) { |args| … } → other_obj

Executes the block with self set to obj, passing args as parameters to the block.

class Dummy < BasicObject

def initialize

@iv = 33

end

def double_and_call(value, &block)

instance_exec(value*2, &block)

end

end

d = Dummy.new

d.double_and_call(22) do |param|

::Kernel::puts "Parameter = #{param}"

::Kernel::puts "@iv = #{@iv}"

end

Produces:

Parameter = 44

@iv = 33

__send__

  • obj.__send__(symbol <, args>* <, &block> ) → other_obj

Invokes the method identified by symbol, passing it any arguments and block.

class Klass < BasicObject

def hello(*args)

"Hello " + args.join(' ')

end

end

k = Klass.new

k.__send__ :hello, "gentle", "readers" # => "Hello gentle readers"

BasicObject: Private instance methods

method_missing

  • method_missing(symbol <, *args> ) → other_obj

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. method_missing can be used to implement proxies, delegators, and forwarders. It can also be used to simulate the existence of methods in the receiver, as the example at the start of this section shows.

singleton_method_added

  • singleton_method_added(symbol )

Invoked as a callback whenever a singleton method is added to the receiver.

module Chatty

def Chatty.singleton_method_added(id)

puts "Adding #{id} to #{self.name}"

end

def self.one() end

def two() end

end

def Chatty.three() end

Produces:

Adding singleton_method_added to Chatty

Adding one to Chatty

Adding three to Chatty

You can add the hook to any object:

obj = "cat"

def obj.singleton_method_added(id)

puts "Adding #{id} to #{self}"

end

def obj.speak

puts "meow"

end

Produces:

Adding singleton_method_added to cat

Adding speak to cat

singleton_method_removed

  • singleton_method_removed(symbol )

Invoked as a callback whenever a singleton method is removed from the receiver.

module Chatty

def Chatty.singleton_method_removed(id)

puts "Removing #{id}"

end

def self.one() end

def two() end

def Chatty.three() end

class <<self

remove_method :three

remove_method :one

end

end

Produces:

Removing three

Removing one

singleton_method_undefined

  • singleton_method_undefined(symbol )

Invoked as a callback whenever a singleton method is undefined in the receiver.

module Chatty

def Chatty.singleton_method_undefined(id)

puts "Undefining #{id}"

end

def Chatty.one() end

class << self

undef_method(:one)

end

end

Produces:

Undefining one

Class Bignum < Integer

Bignum objects hold integers outside the range of Fixnum—Bignum objects are created automatically when integer calculations would otherwise overflow. When a calculation involving Bignum objects returns a result that will fit in a Fixnum, the result is automatically converted.

For the purposes of the bitwise operations and [ ] , a Bignum is treated as if it were an infinite-length bitstring with 2’s complement representation.

While Fixnum values are immediate, Bignum objects are not—assignment and parameter passing work with references to objects, not the objects themselves.

Bignum: Instance methods

Arithmetic operations

Performs various arithmetic operations on big.

big

+

number

Addition

big

--

number

Subtraction

big

*

number

Multiplication

big

/

number

Division

big

%

number

Modulo

big

**

number

Exponentiation

big

-@

Unary minus

Bit operations

Performs various operations on the binary representations of the Bignum.

~ big

Invert bits

big

|

number

Bitwise or

big

&

number

Bitwise and

big

^

number

Bitwise exclusive or

big

<<

number

Left-shift number bits

big

>>

number

Right-shift number bits (with sign extension)

<=>

  • big<=> number → -1, 0, +1, or nil

Comparison—Returns -1, 0, or +1 depending on whether big is less than, equal to, or greater than number. This is the basis for the tests in Comparable.

==

  • big== objtrue or false

Returns true only if obj has the same value as big. Contrast this with Bignum#eql?, which requires obj to be a Bignum.

68719476736 == 68719476736.0 # => true

[ ]

  • big[n ] → 0, 1

Bit Reference—Returns the nth bit in the (assumed) binary representation of big, where big[0] is the least significant bit.

a = 9**15 # that's 9 raised to the 15th power

50.downto(0) do |n|

print a[n]

end

Produces:

000101110110100000111000011110010100111100010111001

abs

  • big.abs →bignum

Returns the absolute value of big.

1234567890987654321.abs # => 1234567890987654321

-1234567890987654321.abs # => 1234567890987654321

div

  • big.div(number ) → other_number

Synonym for Bignum#/.

-1234567890987654321.div(13731) # => -89910996357706

-1234567890987654321.div(13731.0) # => -89910996357706

-1234567890987654321.div(-987654321) # => 1249999989

divmod

  • big.divmod(number ) → array

See Numeric#divmod.

eql?

  • big.eql?(obj ) → true or false

Returns true only if obj is a Bignum with the same value as big. Contrast this with Bignum#==, which performs type conversions.

68719476736.eql? 68719476736 # => true

68719476736 == 68719476736 # => true

68719476736.eql? 68719476736.0 # => false

68719476736 == 68719476736.0 # => true

fdiv

  • big.fdiv(number ) → float

Returns the floating-point result of dividing big by number. Alias for Bignum#quo.

-1234567890987654321.fdiv(13731) # => -89910996357705.52

-1234567890987654321.fdiv(13731.0) # => -89910996357705.52

-1234567890987654321.fdiv(-987654321) # => 1249999989.609375

magnitude

  • big.magnitude →bignum

Returns the magnitude of big (the distance of big from the origin of the number line). Synonym for Bignum#abs. See also Complex#magnitude.

modulo

  • big.modulo(number ) → number

Synonym for Bignum#%.

remainder

  • big.remainder(number ) → other_number

Returns the remainder after dividing big by number.

-1234567890987654321.remainder(13731) # => -6966

-1234567890987654321.remainder(13731.24) # => -9906.22531493148

size

  • big.size →integer

Returns the number of bytes in the machine representation of big.

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

(256**20 - 1).size # => 20

(256**40 - 1).size # => 40

to_f

  • big.to_f →float

Converts big to a Float. If big doesn’t fit in a Float, the result is infinity.

to_s

  • big.to_s(base=10 ) → str

Returns a string containing the representation of big radix base (2 to 36).

12345654321.to_s # => "12345654321"

12345654321.to_s(2) # => "1011011111110110111011110000110001"

12345654321.to_s(8) # => "133766736061"

12345654321.to_s(16) # => "2dfdbbc31"

12345654321.to_s(26) # => "1dp1pc6d"

78546939656932.to_s(36) # => "rubyrules"

Class Binding < Object

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. Access to the variables, methods, value of self, and possibly an iterator block accessible in this context are all retained. Binding objects can be created usingObject#binding and are made available to the callback of Object#set_trace_func and to the block passed to TracePoint.new«2.0».

These binding objects can be passed as the second argument of the Object#eval method, establishing an environment for the evaluation.

class Demo

def initialize(n)

@secret = n

end

def get_binding

return binding()

end

end

k1 = Demo.new(99)

b1 = k1.get_binding

k2 = Demo.new(-3)

b2 = k2.get_binding

# Pass to eval...

eval("@secret", b1) # => 99

# Or eval via binding...

b2.eval("@secret") # => -3

eval("@secret") # => nil

Binding: Instance methods

eval

  • bind.eval(string <, file line> ) → obj

Evaluates the Ruby code in string using the context of bind. Equivalent to calling Object#eval with a second argument of bind. See the start of this section for an example.

Class Class < Module

Classes in Ruby are first-class objects—each is an instance of class Class.

When a new class is defined (typically using class SomeName ... end), an object of type Class is created and assigned to a constant (SomeName, in this case). When Name.new is called to create a new object, the new instance method in Class is run by default, which in turn invokes allocate to allocate memory for the object, before finally calling the new object’s initialize method.

Class: Class methods

new

  • Class.new(super_class=Object ) <> → cls

Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given). If called with a block, that block is used as the body of the class. Within the block, self is set to the class instance.

name = "Dave"

FriendlyClass = Class.new do

define_method :hello do

"Hello, #{name}"

end

end

f = FriendlyClass.new

f.hello # => "Hello, Dave"

Class: Instance methods

allocate

  • cls.allocate →obj

Allocates space for a new object of cls’s class. The returned object must be an instance of cls. Calling new is basically the same as calling the class method allocate to create an object, followed by calling initialize on that new object. You cannot override allocate in normal programs; Ruby invokes it without going through conventional method dispatch.

class MyClass

def self.another_new(*args)

o = allocate

o.send(:initialize, *args)

o

end

def initialize(a, b, c)

@a, @b, @c = a, b, c

end

end

mc = MyClass.another_new(4, 5, 6)

mc.inspect # => "#<MyClass:0x007fbdab10f430 @a=4, @b=5, @c=6>"

new

  • cls.new(<args>* ) → obj

Calls allocate to create a new object of cls’s class and then invokes the newly created object’s initialize method, passing it args.

superclass

  • cls.superclass →super_class or nil

Returns the superclass of cls or returns nil.

Class.superclass # => Module

Object.superclass # => BasicObject

BasicObject.superclass # => nil

Class: Private instance methods

inherited

  • cls.inherited(sub_class )

Invoked by Ruby when a subclass of cls is created. The new subclass is passed as a parameter.

class Top

def self.inherited(sub)

puts "New subclass: #{sub}"

end

end

class Middle < Top

end

class Bottom < Middle

end

Produces:

New subclass: Middle

New subclass: Bottom

Module Comparable

Relies on:

<=>

The Comparable mixin is used by classes whose objects may be ordered. The class must define the <=> operator, which compares the receiver against another object, returning -1, 0, or +1 depending on whether the receiver is less than, equal to, or greater than the other object. Comparable uses <=> to implement the conventional comparison operators (<, <=, ==, >=, and >) and the method between? .

class CompareOnSize

include Comparable

attr :str

def <=>(other)

str.length <=> other.str.length

end

def initialize(str)

@str = str

end

end

s1 = CompareOnSize.new("Z")

s2 = CompareOnSize.new([1,2])

s3 = CompareOnSize.new("XXX")

s1 < s2 # => true

s2.between?(s1, s3) # => true

s3.between?(s1, s2) # => false

[ s3, s2, s1 ].sort # => ["Z", [1, 2], "XXX"]

Comparable: Instance methods

Comparisons

  • obj< other_objecttrue or false
  • obj<= other_objecttrue or false
  • obj== other_objecttrue or false
  • obj>= other_objecttrue or false
  • obj> other_objecttrue or false

Compares two objects based on the receiver’s <=> method.

between?

  • obj.between?(min, max ) → true or false

Returns false if obj <=> min is less than zero or if obj <=> max is greater than zero; returns true otherwise.

3.between?(1, 5) # => true

6.between?(1, 5) # => false

'cat'.between?('ant', 'dog') # => true

'gnu'.between?('ant', 'dog') # => false

Class Complex < Numeric

Represents complex numbers, represented internally as numbers with a real part and an imaginary part, both of which can be any scalar number. Note that scalar comparison operations (<=>, <, and so on) are not defined on complex numbers (which would argue that Complex should not be a subclass of Numeric, but that ship has sailed). Also see the standard library named complex for a way to add complex number support to standard math functions; also see the mathn library for a way of integrating complex numbers into regular arithmetic (so that the square root of -1 returns Complex::I).

v1 = Complex(2,3) # => (2+3i)

v2 = Complex("0+2i") # => (0+2i)

v1 + v2 # => (2+5i)

v1 * v2 # => (-6+4i)

v2**2 # => (-4+0i)

v2**2 == -4 # => true

# Euler's theorem

include Math

E**(PI*Complex::I) # => (-1.0+1.2246467991473532e-16i)

Constants

Complex::I

The imaginary unit.

Complex: Class methods

polar

  • Complex.polar(magnitude, angle ) → complex

Returns the complex number represented by the given polar coordinates.

Complex.polar(1.23, 0.5) # => 1.0794265511251584+0.5896934124831696i

Complex.polar(1, Math::PI/2) # => 6.123233995736766e-17+1.0i

rect

  • Complex.rect(read, imag ) → complex

Returns the complex number represented by the given real and imaginary parts.

Complex.rect(1.23, 0.5) # => 1.23+0.5i

rectangular

  • Complex.rectangular(read, imag ) → complex

Synonym for Complex.rect.

Complex: Instance methods

Arithmetic operations

Performs various arithmetic operations on complex.

complex

+

numeric

Addition

complex

--

numeric

Subtraction

complex

*

numeric

Multiplication

complex

/

numeric

Division

complex

**

numeric

Exponentiation

complex

-@

Unary minus

complex

-+

Unary plus

==

  • complex== othertrue or false

Returns true if complex does equals other, converting other to a complex number if necessary.

Complex::I == Complex(0,1) # => true

Complex::I == Complex(1,0) # => false

Complex(1,0) == 1 # => true

Complex(1,0) == "1" # => false

abs

  • complex.abs →number

Synonym for Complex#magnitude.

abs2

  • complex.abs2 →number

Returns the square of the absolute value (magnitude) of complex.

Complex::I.abs2 # => 1

Complex(1,1).abs2 # => 2

angle

  • complex.angle →number

Returns the angle between the x-axis and a line from the origin to complex. By convention, Complex(0,0).angl} is 0.

Complex(1, 0).angle # => 0.0

Complex(1, 1).angle # => 0.7853981633974483

Complex(0, 1).angle # => 1.5707963267948966

arg

  • complex.arg →number

Synonym for Complex#angle.

conj

  • complex.conj →a_complex

Synonym for Complex#conjugate.

conjugate

  • complex.conjugate →a_complex

Returns the conjugate of complex (the reflection of complex around the x-axis).

Complex::I.conjugate # => (0-1i)

Complex(1,1).conjugate # => (1-1i)

denominator

  • complex.denominator →number

Returns the lowest common multiple of the denominators of the real and imaginary parts of complex.

Complex("1/3+1/4i").denominator # => 12

Complex(-2, 4).denominator # => 1

eql?

  • complex.eql(other ) → true or false

Returns true only if other is a complex number with real and imaginary parts eql? to complex’s.

Complex(1, 0).eql?(Complex(1,0)) # => true

Complex(1, 0).eql?(Complex(1.0, 0)) # => false

Complex(1, 0).eql?(1) # => false

Complex(1, 0) == Complex(1,0) # => true

Complex(1, 0) == Complex(1.0, 0) # => true

Complex(1, 0) == 1 # => true

fdiv

  • complex.fdiv(other ) → a_complex

Returns complex / other after converting the real and imaginary parts of complex to floats. (Contrast with Complex#quo.)

c1 = Complex(1, 2)

c2 = Complex(2, 2)

c1 /c2 # => ((3/4)+(1/4)*i)

c1.fdiv(c2) # => (0.75+0.25i)

imag

  • complex.imag →number

Returns the imaginary part of complex.

Complex(2, -3).imag # => -3

imaginary

  • complex.imaginary →number

Synonym for Complex#imag.

magnitude

  • complex.magnitude →int or float

Returns the magnitude of complex (the distance of complex from the origin of the number line). The positive square root of real2 + imag2.

Complex(1, 1).magnitude # => 1.4142135623730951

Complex(3, 4).magnitude # => 5.0

Complex::I.magnitude # => 1

numerator

  • complex.numerator →a_complex

Returns the numerator, treating the real and complex parts of complex as fractions to be combined over a common denominator.

c = Complex('2/3+3/4i')

c.numerator # => (8+9i)

c.denominator # => 12

phase

  • complex.phase → [magnitude,angle ]

Returns the phase angle of complex (the angle between the positive x-axis and the line from the origin to (real, imag)), measured in radians.

Complex(3, 4).phase # => 0.9272952180016122

Complex(-3, 4).phase # => 2.214297435588181

polar

  • complex.polar → [magnitude, angle ]

Returns complex as polar coordinates.

Complex(1,1).polar # => [1.4142135623730951, 0.7853981633974483]

Complex(-2,-3).polar # => [3.605551275463989, -2.158798930342464]

quo

  • complex.quo(other ) → a_complex

Returns complex / other after converting the real and imaginary parts of complex to rational numbers. (Contrast with Complex#fdiv.)

c1 = Complex(1, 2)

c2 = Complex(2, 2)

c1 /c2 # => ((3/4)+(1/4)*i)

c1.quo(c2) # => ((3/4)+(1/4)*i)

rationalize

  • complex.rationalize(eps=nil ) → rational

Returns the real part of complex as a rational number, raising an exception if the imaginary part is not zero. The argument is always ignored. Effectively a synonym for Complex.to_r.

Complex(2.5, 0).rationalize # => (5/2)

rect

  • complex.rect → [complex.real, complex.imag ]

Returns an array containing the real and imaginary components of complex.

Complex::I.rect # => [0, 1]

rectangular

  • complex.rectangular → [complex.real, complex.imag ]

Synonym for Complex#rect.

real

  • complex.real →number

Returns the real part of complex.

Complex(2, 3).real # => 2

real?

  • complex.real? →false

Complex numbers are never real numbers (even if their imaginary part is zero).

Complex(1, 1).real? # => false

Complex(1, 0).real? # => false

to_f

  • complex.to_f →float

Returns the real part of complex as a float, raising an exception if the imaginary part is not zero.

Complex(2, 0).to_f # => 2.0

to_i

  • complex.to_i →integer

Returns the real part of complex as an integer, raising an exception if the imaginary part is not zero.

Complex(2.2, 0).to_i # => 2

to_r

  • complex.to_r →rational

Returns the real part of complex as a rational number, raising an exception if the imaginary part is not zero.

Complex(2.5, 0).to_r # => (5/2)

Class Dir < Object

Objects of class Dir are directory streams representing directories in the underlying file system. They provide a variety of ways to list directories and their contents. See also File.

The directory used in these examples contains the two regular files (config.h and main.rb), the parent directory (..), and the directory itself (.).

Mixes in

Enumerable

all?, any?, chunk, collect, collect_concat, count, cycle, detect, drop, drop_while, each_cons, each_entry, each_slice, each_with_index, each_with_object, entries, find, find_all, find_index, first, flat_map, grep, group_by, include?, inject, lazy, map, max, max_by, member?, min, min_by, minmax, minmax_by, none?, one?, partition, reduce, reject, reverse_each, select, slice_before, sort, sort_by, take, take_while, to_a, zip

Dir: Class methods

[ ]

  • Dir[glob_pattern ] → array

Equivalent to calling Dir.glob(glob_pattern,0).

chdir

  • Dir.chdir(< dir> ) → 0
  • Dir.chdir(< dir> ) { |path| … } → obj

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. Raises a 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 multithreaded program an error will be raised if a thread attempts to open a chdir block while another thread has one open. This is because the underlying operating system only understands the concept of a single current working directory at any one time.

Dir.chdir("/private/var/log") # => 0

Dir.pwd # => "/private/var/log"

Dir.chdir("/private/tmp") do

Dir.pwd # => "/private/tmp"

Dir.chdir("/usr") do

Dir.pwd # => "/usr"

end

Dir.pwd # => "/private/tmp"

end

Dir.pwd # => "/private/var/log"

chroot

  • Dir.chroot(dirname ) → 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.chdir("/production/secure/root")

Dir.chroot("/production/secure/root") #=> 0

Dir.pwd #=> "/"

delete

  • Dir.delete(dirname ) → 0

Deletes the named directory. Raises a subclass of SystemCallError if the directory isn’t empty.

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") # => [".", "..", ".svn", "config.h", "main.rb"]

exist?

  • Dir.exist?(path ) → true or false

Returns true if path exists and is a directory. Alias for File.directory?.

Dir.exist?("/tmp") # => true

Dir.exist?("/temp") # => false

exists?

  • Dir.exists?(path ) → true or false

Alias for Dir.exist?.

foreach

  • Dir.foreach(dirname ) { |filename| … } → nil

Calls the block once for each entry in the dirname, passing the filename as a parameter.

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

Produces:

Got .

Got ..

Got .svn

Got config.h

Got main.rb

getwd

  • Dir.getwd →dirname

Returns a string containing the canonical path to the current working directory of this process. Note that on some operating systems this name may not be the name you gave to Dir.chdir. On OS X, for example, /tmp is a symlink.

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

Dir.getwd # => "/private/tmp"

glob

  • Dir.glob(glob_pattern, <flags> ) → array
  • Dir.glob(glob_pattern, <flags> ) { |filename| … } → false

Returns the filenames found by expanding the pattern given in glob_pattern, either as elements in 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. Case sensitivity depends on your system (so File::FNM_CASEFOLD is ignored). Metacharacters in the pattern are as follows:

*

Any sequence of characters in a filename: * 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 their name.

**

Matches zero or more directories (so **/fred matches a file named fred in or below the current directory).

?

Matches any one character in a filename.

[chars]

Matches any one of chars. If the first character in chars is ^, matches any character not in the remaining set.

{patt,...}

Matches one of the patterns specified between braces. These patterns may contain other metacharacters.

\

Removes any special significance in the next character.

Dir.chdir("testdir") # => 0

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) # => [".", "..", ".svn", "config.h", "main.rb"]

Dir.chdir("..") # => 0

Dir.glob("code/**/fib*.rb") # => ["code/irb/fibonacci_sequence.rb",

# .. "code/rdoc/fib_example.rb"]

Dir.glob("**/rdoc/fib*.rb") # => ["code/rdoc/fib_example.rb"]

home

  • Dir.home(<user_name> ) → string

Returns the home directory of the given user (or the current user if no argument is given).

Dir.home # => "/Users/dave"

Dir.home("nobody") # => "/var/empty"

mkdir

  • Dir.mkdir(dirname <, permissions> ) → 0

Makes a new directory named dirname, with permissions specified by the optional parameter permissions. The permissions may be modified by the value of File.umask and are ignored on Windows. Raises a SystemCallError if the directory cannot be created. See also the discussion of permissions.

new

  • Dir.new(dirname <, :encoding => enc> ) → dir

Returns a new directory object for the named directory. The optional hash parameter lets you specify the encoding used by filenames. If not given, it defaults to the file system local on the current machine.

open

  • Dir.open(dirname <, :encoding => enc>) → dir
  • Dir.open(dirname <, :encoding => enc>) { |dir| … } → obj

With no block, open is a synonym for Dir.new. If a block is present, it is passed dir as a parameter. The directory is closed at the end of the block, and Dir.open returns the value of the block.

pwd

  • Dir.pwd →dirname

Synonym for Dir.getwd.

rmdir

  • Dir.rmdir(dirname ) → 0

Synonym for Dir.delete.

unlink

  • Dir.unlink(dirname ) → 0

Synonym for Dir.delete.

Dir: Instance methods

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

each

  • dir.each { |filename| … } →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 {|name| puts "Got #{name}" }

Produces:

Got .

Got ..

Got .svn

Got config.h

Got main.rb

path

  • dir.path → dirname

Returns the path parameter passed to dir’s constructor.

d = Dir.new("..")

d.path # => ".."

pos

  • dir.pos →int

Synonym for Dir#tell.

pos=

  • dir.pos(int ) → int

Synonym for Dir#seek but returns the position parameter.

d = Dir.new("testdir") # => #<Dir:testdir>

d.read # => "."

i = d.pos # => 1

d.read # => ".."

d.pos = i # => 1

d.read # => ".."

read

  • dir.read →filename 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 # => ".svn"

rewind

  • dir.rewind →dir

Repositions dir to the first entry.

d = Dir.new("testdir")

d.read # => "."

d.rewind # => #<Dir:testdir>

d.read # => "."

seek

  • dir.seek(int ) → dir

Seeks to a particular location in dir. int must be a value returned by Dir#tell (it is not necessarily a simple index into the entries).

d = Dir.new("testdir") # => #<Dir:testdir>

d.read # => "."

i = d.tell # => 1

d.read # => ".."

d.seek(i) # => #<Dir:testdir>

d.read # => ".."

tell

  • dir.tell →int

Returns the current position in dir. See also Dir#seek.

d = Dir.new("testdir")

d.tell # => 0

d.read # => "."

d.tell # => 1

to_path

  • dir.to_path → dirname

Synonym for Dir.path.

Class Encoding < Object

An encoding describes how to map the binary data in the internal representation of strings into characters. Ruby has support for a large number of encodings built in—others can be loaded dynamically at runtime.

Encodings are identified by name (UTF-8 or ISO-8859-1, for example). They are represented by encoding objects. The Encoding class contains predefined constants for these encoding objects. Often there are multiple objects for the same encoding. For example, the constants Encoding::IBM860 and Encoding::CP860 are both representations of the encoding named IBM860. In the two-part table Table 15, Encoding names and class names, the first column shows the names of the encodings, and the second column lists the names on the constants in the Encoding class for the corresponding encoding object(s). An entry such as ISO-8859-1 -- 11 indicates that there are eleven separate encodings (with the obvious names).

Encodings are used when opening files, creating strings, and so on. The methods that accept an encoding as a parameter will take either an encoding name or an encoding object. Use of the object is marginally faster.

Chapter 17, Character Encoding is devoted to a discussion of encodings.

Encoding: Class methods

aliases

  • Encoding.aliases →hash

Returns a hash whose keys are aliases for encodings and whose values are the corresponding base encoding names.

Encoding.aliases["BINARY"] # => "ASCII-8BIT"

compatible?

  • Encoding.compatible?(str1, str2 ) → enc or nil

Determines whether two strings have compatible encodings (meaning, for example, that you could concatenate them). Returns the encoding of the string that would result from the concatenation or nil if the strings are not compatible.

# encoding: utf-8

ascii1 = "ant"

ascii2 = "bee"

iso = "\xee"

iso.force_encoding(Encoding::ISO_8859_1)

utf = "∂og"

Encoding.compatible?(ascii1, ascii2) # => #<Encoding:UTF-8>

Encoding.compatible?(ascii1, iso) # => #<Encoding:ISO-8859-1>

Encoding.compatible?(ascii1, utf) # => #<Encoding:UTF-8>

Encoding.compatible?(iso, utf) # => nil

Table 15. Encoding names and class names

Encoding

Class name(s)

Encoding

Class name(s)

ASCII-8BIT

ASCII_8BIT, BINARY

Big5

Big5, BIG5

Big5-HKSCS

Big5_HKSCS, BIG5_HKSCS, Big5_HKSCS_2008, BIG5_HKSCS_2008

Big5-UAO

Big5_UAO, BIG5_UAO

CP50220

CP50220

CP50221

CP50221

CP51932

CP51932

CP850

CP850, IBM850

CP852

CP852

CP855

CP855

CP949

CP949

CP950

CP950

CP951

CP951

Emacs-Mule

Emacs_Mule, EMACS_MULE

EUC-JP

EUC_JP, EucJP, EUCJP

EUC-JP-2004

EUC_JP_2004, EUC_JISX0213

EUC-KR

EUC_KR, EucKR, EUCKR

EUC-TW

EUC_TW, EucTW, EUCTW

eucJP-ms

EucJP_ms, EUCJP_MS, EUC_JP_MS

GB12345

GB12345

GB18030

GB18030

GB1988

GB1988

GB2312

EUC_CN, EucCN, EUCCN

GBK

GBK, CP936

IBM437

IBM437, CP437

IBM737

IBM737, CP737

IBM775

IBM775, CP775

IBM852

IBM852

IBM855

IBM855

IBM857

IBM857, CP857

IBM860 -- 6

IBM860 -- 6, CP8600 -- 6

IBM869

IBM869, CP869

ISO-2022-JP

ISO_2022_JP, ISO2022_JP

ISO-2022-JP-2

ISO_2022_JP_2, ISO2022_JP2

ISO-2022-JP-KDDI

ISO_2022_JP_KDDI

ISO-8859-1 -- 11

ISO8859_1 -- 11

ISO-8859-13 -- 16

ISO8859_13 -- 16

KOI8-R

KOI8_R, CP878

KOI8-U

KOI8_U

macCentEuro

MacCentEuro, MACCENTEURO

macCroatian

MacCroatian, MACCROATIAN

macCyrillic

MacCyrillic, MACCYRILLIC

macGreek

MacGreek, MACGREEK

macIceland

MacIceland, MACICELAND

MacJapanese

MacJapanese, MACJAPANESE, MacJapan, MACJAPAN

macRoman

MacRoman, MACROMAN

macRomania

MacRomania, MACROMANIA

macThai

MacThai, MACTHAI

macTurkish

MacTurkish, MACTURKISH

macUkraine

MacUkraine, MACUKRAINE

Shift_JIS

Shift_JIS, SHIFT_JIS

SJIS-DoCoMo

SJIS_DoCoMo, SJIS_DOCOMO

SJIS-KDDI

SJIS_KDDI

SJIS-SoftBank

SJIS_SoftBank, SJIS_SOFTBANK

stateless-ISO-2022-JP

Stateless_ISO_2022_JP, STATELESS_ISO_2022_JP

stateless-ISO-2022-JP-KDDI

Stateless_ISO_2022_JP_KDDI, STATELESS_ISO_2022_JP_KDDI

TIS-620

TIS_620

US-ASCII

US_ASCII, ASCII, ANSI_X3_4_1968

UTF-16

UTF_16

UTF-16BE

UTF_16BE, UCS_2BE

UTF-16LE

UTF_16LE

UTF-32

UTF_32

UTF-32BE

UTF_32BE, UCS_4BE

UTF-32LE

UTF_32LE, UCS_4LE

UTF-7

UTF_7, CP65000

UTF-8

UTF_8, CP65001

UTF8-DoCoMo

UTF8_DoCoMo, UTF8_DOCOMO

UTF8-KDDI

UTF8_KDDI

UTF8-MAC

UTF8_MAC, UTF_8_MAC, UTF_8_HFS

UTF8-SoftBank

UTF8_SoftBank, UTF8_SOFTBANK

Windows-1250 -- 1258

Windows_1250 -- 1258, WINDOWS_1250 -- 1258, CP1250 -- 1258

Windows-31J

Windows_31J, WINDOWS_31J, CP932, CsWindows31J, CSWINDOWS31J, SJIS, PCK

Windows-874

Windows_874, WINDOWS_874, CP874

default_external

  • Encoding.default_external →enc

Returns the default external encoding, used when reading and writing data from I/O streams.

Encoding.default_external # => #<Encoding:UTF-8>

default_external=

  • Encoding.default_external =enc

Sets the default external encoding.

default_internal

  • Encoding.default_internal →enc or nil

Returns the default internal encoding, used when transcoding data read and written. Returns nil if no default encoding is set.

default_internal=

  • Encoding.default_internal =enc

Sets the default internal encoding.

Encoding.default_internal = 'utf-8'

Encoding.default_internal # => #<Encoding:UTF-8>

find

  • Encoding.find(name ) → enc

Returns the encoding object for the given encoding name or throws an ArgumentError.

Encoding.find("Shift_JIS") # => #<Encoding:Shift_JIS>

list

  • Encoding.list →array

Returns a list of the encoding objects loaded into the current interpreter.

locale_charmap

  • Encoding.locale_charmap →name

Returns the name of the charmap of the current locale. This is normally set externally, often in an environment variable or other operating-system context.

ENV["LANG"] # => "en_US.UTF-8"

Encoding.locale_charmap # => "UTF-8"

name_list

  • Encoding.name_list →array

Returns a list of the names of loaded encodings.

Encoding.name_list.sort.first(5) # => ["646", "ANSI_X3.4-1968", "ASCII",

# .. "ASCII-8BIT", "BINARY"]

Encoding: Instance methods

ascii_compatible?

  • enc.ascii_compatible? → true or false

Returns true if the lower 127 codepoints in the encoding overlay the ASCII character set.

Encoding::UTF_8.ascii_compatible? # => true

Encoding::SJIS.ascii_compatible? # => true

Encoding::UTF_7.ascii_compatible? # => false

dummy?

  • enc.dummy? → true or false

Dummy encodings are placeholders for encodings that cannot be handled properly by the current mechanism of Ruby multinationalization, often because they are stateful.

Encoding::UTF_7.dummy? # => true

Encoding::UTF_8.dummy? # => false

name

  • enc.name →string

Returns the name of enc.

Encoding::UTF_8.name # => "UTF-8"

Encoding::CP65001.name # => "UTF-8"

names

  • enc.names → [<string>+ ]

Returns the name of enc, along with the names of enc’s aliases.

Encoding::ISO8859_1.names # => ["ISO-8859-1", "ISO8859-1"]

Encoding::ASCII.names # => ["US-ASCII", "ASCII", "ANSI_X3.4-1968", "646"]

replicate

  • enc.replicate(name ) → new_encoding

Create a copy of the encoding enc with the given name (which must be unique).

Module Enumerable

Relies on:

each, <=>

The Enumerable mixin provides collection classes with 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 , sort , or sort_by is used, the objects in the collection must also implement a meaningful <=> operator, because these methods rely on an ordering between members of the collection.

Ruby 1.9 adds a substantial number of methods to this module, as well as changing the semantics of many others. Even experienced Ruby programmers should probably read this section carefully.

Enumerable: Instance methods

all?

  • enum.all?<obj> → 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 no collection member is false or nil).

[ nil, true, 99 ].all? # => false

any?

  • enum.any?<obj> → true or false

Passes elements of the collection in turn to the given block. The method returns true (and stops calling the block) 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). See also Enumerable#none? and Enumerable#one?.

[ nil, true, 99 ].any? # => true

chunk

  • enum.chunk { |element| … } →enumerator
  • enum.chunk(state ) { |element, state| … } → enumerator

Passes each element of enum to the block. Use the value returned from the block as a key, and group successive elements with the same key together. The enumerator that is returned will yield the key and the successive values corresponding to that key. Here’s a simple example that returns sequences of words that have the same length:

enum = %w{ ant bee coyote dophin elk }.chunk(&:size)

enum.next # => [3, ["ant", "bee"]]

enum.next # => [6, ["coyote", "dophin"]]

enum.next # => [3, ["elk"]]

If the block returns the values nil or :_separator, the corresponding value is not stored in the output enumerator, and a new output element is started.

enum = [ 1, 2, 3, 4, 5 ].chunk {|element| element.odd? ? :odd : :_separator}

enum.to_a # => [[:odd, [1]], [:odd, [3]], [:odd, [5]]]

The following example uses the fact that a failing pattern match returns nil:

# This code reads its own source and returns each comment block

File.foreach(__FILE__).chunk do |line|

# A comment is a group of consecutive

# lines starting with '#'

line =~ /^\s*#/

end.each do |_, lines|

p lines

end

Produces:

["# This code reads its own source and returns each comment block\n"]

[" # A comment is a group of consecutive\n", " # lines starting with '#'\n"]

If the block returns :_alone, this value is put into its own output element—it will not be grouped with the previous element even if that element’s block also returned :_alone.

enum = [ 1, 2, 3 ].chunk { :_alone }

enum.to_a # => [[:_alone, [1]], [:_alone, [2]], [:_alone, [3]]]

If a state parameter is present, it is passed as the second parameter to every call to the block, permitting state to be maintained across calls.

See also Enumerable.slice_before.

collect

  • enum.collect { |obj| … } →array or enumerator

Returns a new array containing the results of running block once for every element in enum. Returns an Enumerator object if no block is given.

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

(1..4).collect { "cat" } # => ["cat", "cat", "cat", "cat"]

(1..4).collect(&:even?) # => [false, true, false, true]

collect_concat

  • enum.collect_concat { |obj| … } →array
  • enum.collect_concat →enumerator

Synonym for (the better named) Enumerable.flat_map.

count

  • enum.count(obj ) → int
  • enum.count { |obj| … } →int

Returns the count of objects in enum that equal obj or for which the block returns a true value. Returns the count of all elements in enum if neither a block nor an argument is given.

(1..4).count # => 4

(1..4).count(3) # => 1

(1..4).count {|obj| obj > 2 } # => 2

cycle

  • enum.cycle { |obj| … } → nil orenumerator
  • enum.cycle(times ) { |obj| … } → nil or enumerator

Returns nil if enum has no elements; otherwise, passes the elements, one at a time, to the block, repeating when it reaches the end. The number of times it repeats is set by the parameter. If the parameter is missing, cycles forever. Equivalent to enum.to_a.cycle. See also Array#cycle. Returns an Enumerator object if no block is given.

('a'..'c').cycle(2) # => #<Enumerator: "a".."c":cycle(2)>

('a'..'c').cycle(2).to_a # => ["a", "b", "c", "a", "b", "c"]

detect

  • enum.detect(ifnone = nil ) { |obj| … } → obj or nil or enumerator

Passes each entry in enum to block. Returns the first for which block is not false. Returns nil if no object matches unless the proc ifnone is given, in which case it is called and its result is returned. Returns an Enumerator object if no block is given.

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

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

sorry = lambda { "not found" }

(1..10).detect(sorry) {|i| i > 50} # => "not found"

drop

  • enum.drop(n ) → an_array

Returns an array containing all but the first n elements of enum.

[ 1, 1, 2, 3, 5, 8, 13 ].drop(4) # => [5, 8, 13]

[ 1, 1, 2, 3, 5, 8, 13 ].drop(99) # => []

drop_while

  • enum.drop_while { |item| … } →an_array or enumerator

Passes elements in turn to the block until the block does not return a true value. Starting with that element, copies the remainder to an array and returns it. Returns an Enumerator object if no block is given.

[ 1, 1, 2, 3, 5, 8, 13 ].drop_while {|item| item < 6 } # => [8, 13]

each_cons

  • enum.each_cons(length ) { |array| … } → nil or enumerator

Passes to the block each consecutive subarray of size length from enum. Returns an Enumerator object if no block is given.

(1..4).each_cons(2) {|array| p array }

Produces:

[1, 2]

[2, 3]

[3, 4]

each_entry

  • enum.each_entry { |element| … } →enum
  • enum.each_entry →enumerator

Repeatedly calls enum.each , passing the result to the block. If each returns a single value, it is passed unchanged to the block. If a call to each returns multiple values, they are packaged into an array and passed to the block.

class Generator

include Enumerable

def each

yield 1

yield 2, 3

yield 4

end

end

g = Generator.new

g.each {|entry| print entry, " : "}

puts

g.each_entry {|entry| print entry, " : "}

Produces:

1 : 2 : 4 :

1 : [2, 3] : 4 :

each_slice

  • enum.each_slice(length ) { |array| … } → nil or enumerator

Divides enum into slices of size length, passing each in turn to the block. Returns an Enumerator object if no block is given.

(1..10).each_slice(4) {|array| p array }

Produces:

[1, 2, 3, 4]

[5, 6, 7, 8]

[9, 10]

each_with_index

  • enum.each_with_index(<args>* ) { |obj, index| … }
  • enum or enumerator

Calls block, passing in successive items from enum and the corresponding index. If any arguments are given, they are passed to each during the iteration.Returns an Enumerator object if no block is given.

%w(cat dog wombat).each_with_index do |item, index|

puts "#{item} is at position #{index}"

end

Produces:

cat is at position 0

dog is at position 1

wombat is at position 2

each_with_object

  • enum.each_with_object(memo ) → memo or enumerator

Calls block with the item and the memo object, for each item in enum. Returns an Enumerator object if no block is given.

hash = %w(cat dog wombat).each_with_object({}) do |item, memo|

memo[item] = item.upcase.reverse

end

hash # => {"cat"=>"TAC", "dog"=>"GOD", "wombat"=>"TABMOW"}

entries

  • enum.entries →array

Synonym for Enumerable#to_a.

find

  • enum.find(ifnone = nil ) { |obj| … } → obj or nil

Synonym for Enumerable#detect.

find_all

  • enum.find_all { |obj| … } →array or enumerator

Returns an array containing all elements of enum for which block is not false (see also Enumerable#reject). Returns an Enumerator object if no block is given.

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

find_index

  • enum.find_index(obj ) → int or nil
  • enum.find_index { |obj| … } →int or nil or enumerator

Returns the index of the first object in arr that is == to obj or for which the block returns a true value. Returns nil otherwise. See also Enumerable#reject. Returns an Enumerator object if no block is given.

%w{ant bat cat dog}.find_index {|item| item =~ /g/ } # => 3

%w{ant bat cat dog}.find_index {|item| item =~ /h/ } # => nil

first

  • enum.first →an_object or nil
  • enum.first(n ) → an_array

With no parameters, returns the first item of enum or nil. With a parameter, returns the first n items of enum.

%w{ant bat cat dog}.first # => "ant"

%w{ant bat cat dog}.first(2) # => ["ant", "bat"]

flat_map

  • enum.flat_map { |obj| … } →array
  • enum.flat_map →enumerator

Passes each element in enum to the block. If the returned value is an array (or is compatible with an array), append each element to the result; otherwise, append the block return value to the result. The effect is a single-level flattening of any returned value. If no block is given, return an enumerator.

[ 1, 2, 3 ].flat_map {|e| [ e, 100-e ]} # => [1, 99, 2, 98, 3, 97]

grep

  • enum.grep(pattern ) → array
  • enum.grep(pattern ) { |obj| … } → 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_SET, :SEEK_CUR, :SEEK_END]

res = c.grep(/SEEK/) {|v| IO.const_get(v) }

res # => [0, 1, 2]

[ 123, 9**11, 12.34 ].grep(Integer) # => [123, 31381059609]

group_by

  • enum.group_by { |item| … } →hash or enumerator

Partitions enum by calling the block for each item and using the result returned by the block to group the items into buckets. Returns a hash where the keys are the objects returned by the block, and the values for a key are those items for which the block returned that object. Returns an Enumerator object if no block is given.

p (1..5).group_by {|item| item.even? ? "even" : "odd" }

Produces:

{"odd"=>[1, 3, 5], "even"=>[2, 4]}

include?

  • enum.include?(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

inject

  • enum.inject(initial) { |memo, obj| … } → obj
  • enum.inject(initial, sym ) → obj
  • enum.inject { |memo,obj| … } → obj
  • enum.inject(sym ) → obj

Combines the items in enum by iterating over them. For each item, passes an accumulator object (called memo in the examples) and the item itself to the block or invokes memo.send(sym, obj). At each step, memo is set to the value returned by the block on the previous step. The value returned by inject is the final value returned by the block. The first two forms let you supply an initial value for memo. The second two forms use the first element of the collection as the initial value (and skip that element while iterating). Some languages call this operation foldl or reduce . Ruby supports the latter as an alias for inject .

# Sum some numbers. These forms do the same thing

(5..10).inject(0) {|sum, n| sum + n } # => 45

(5..10).inject {|sum, n| sum + n } # => 45

(5..10).inject(0, :+) # => 45

(5..10).inject(:+) # => 45

# Multiply some numbers

(5..10).inject(1) {|product, n| product * n } # => 151200

(5..10).inject(&:*) # => 151200

# find the longest word

longest_word = %w{ cat sheep bear }.inject do |memo, word|

memo.length > word.length ? memo : word

end

longest_word # => "sheep"

# find the length of the longest word

longest_length = %w{ cat sheep bear }.inject(0) do |memo, word|

memo >= word.length ? memo : word.length

end

longest_length # => 5

lazy

  • enum.lazy →lazy_enum

Returns a lazy enumerator for this enumerable object. See the description of lazy enumerators for more details.«2.0»

map

  • enum.map { |obj| … } →array

Synonym for Enumerable#collect.

max

  • enum.max →obj
  • enum.max { |a,b| … } →obj

Returns the object in enum with the maximum value. The first form assumes all objects implement <=> ; 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"

max_by

  • enum.max_by { |item| … } →obj or enumerator

Passes each item in the collection to the block. Returns the item corresponding to the largest value returned by the block. Returns an Enumerator object if no block is given.

a = %w(albatross dog horse fox)

a.max_by {|item| item.length } # => "albatross"

a.max_by {|item| item.reverse } # => "fox"

member?

  • enum.member?(obj ) → true or false

Synonym for Enumerable#include?.

min

  • enum.min →obj
  • enum.min { |a,b| … } →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"

min_by

  • enum.min_by { |item| … } →obj or enumerator

Passes each item in the collection to the block. Returns the item corresponding to the smallest value returned by the block. Returns an Enumerator object if no block is given.

a = %w(albatross dog horse fox)

a.min_by {|item| item.length } # => "dog"

a.min_by {|item| item.reverse } # => "horse"

minmax

  • enum.minmax → [min, max ]
  • enum.minmax { |a,b| … } → [min, max ]

Compares the elements of enum using either <=> or the given block, returning the minimum and maximum values.

a = %w(albatross dog horse)

a.minmax # => ["albatross", "horse"]

a.minmax {|a,b| a.length <=> b.length } # => ["dog", "albatross"]

minmax_by

  • enum.minmax_by { |item| … } → [min, max ] or enumerator

Passes each item in enum to the block. Returns the items corresponding to the smallest and largest values returned by the block. Returns an Enumerator object if no block is given.

a = %w(albatross dog horse fox)

a.minmax_by {|item| item.length } # => ["dog", "albatross"]

a.minmax_by {|item| item.reverse } # => ["horse", "fox"]

none?

  • enum.none?<obj> → true or false

Passes each element of the collection to the given block. The method returns true if the block never returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is, none? will return false if any of the collection members is not false or nil). See alsoEnumerable#any? and Enumerable#one?.

[ nil, true, 99 ].none? # => false

one?

  • enum.one?<obj> → true or false

Passes each element of the collection to the given block. The method returns true if the block returns true exactly one time. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is, one? will return true if at least one of the collection members is not false or nil). See alsoEnumerable#any? and Enumerable#none?.

[ nil, nil, 99 ].one? # => true

partition

  • enum.partition { |obj| … } → [true_array, false_array ] or enumerator

Returns two arrays, the first containing the elements of enum for which the block evaluates to true and the second containing the rest. Returns an Enumerator object if no block is given.

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

reduce

  • enum.reduce(initial) { |memo, obj| … } → obj
  • enum.reduce(initial, sym ) → obj
  • enum.reduce { |memo,obj| … } → obj
  • enum.reduce(sym ) → obj

Synonym for Enumerable#inject.

reject

  • enum.reject { |obj| … } →array or enumerator

Returns an array containing the elements of enum for which block is false (see also Enumerable#find_all). Returns an Enumerator object if no block is given.

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

reverse_each

  • enum.reverse_each { |obj| … } →enum

Invokes the block with the elements of enum in reverse order. Creates an intermediate array internally, so this might be expensive on large collections. Returns an Enumerator object if no block is given.

(1..5).reverse_each {|i| print i, " " }

Produces:

5 4 3 2 1

select

  • enum.select { |obj| … } →array

Synonym for Enumerable#find_all.

slice_before

  • enum.slice_before(pattern ) → enumerator
  • enum.slice_before(<state> ) { |element, <state>| … } → enumerator

Chunks enum into a set of arrays and returns an enumerator of those arrays. A new array is started whenever the next element matches the pattern (using === when the block returns true). Think of this as a generalized String#split method.

p DATA.map(&:chomp).slice_before(/\w:/).to_a

__END__

colors

red

yellow

pitches

high

low

middle

Produces:

[["colors", " red", " yellow", "pitches", " high", " low", " middle"]]

Collapse sequences of three or more consecutive things into first--last.

input = [ 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 15 ]

def returning(value) # helper returns its parameter after calling the block

yield

value

end

State = Struct.new(:last_value) # Need to box the value to make it mutable

# divide the input into runs of consecutive numbers

slices = input.slice_before(State.new(input.first)) do |value, state|

returning(value != state.last_value.succ) do

state.last_value = value

end

end

p(slices.map do |runs| # replace runs of 3 or more with first–last

runs.size < 3 ? runs : "#{ runs.first }-#{ runs.last }"

end.join(', '))

Produces:

"1-5, 8, 9, 11-13, 15"

sort

  • enum.sort →array
  • enum.sort { |a, b| … } →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. See also Enumerable#sort_by.

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

sort_by

  • enum.sort_by { |obj| … } →array

Sorts enum using keys generated by mapping the values in enum through the given block, using the result of that block for element comparison.

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

Internally, 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'

a = (1..100000).map {rand(100000)}

Benchmark.bm(10) do |b|

b.report("Sort") { a.sort }

b.report("Sort by") { a.sort_by {|val| val } }

end

Produces:

user system total real

Sort 0.030000 0.000000 0.030000 ( 0.026899)

Sort by 0.140000 0.000000 0.140000 ( 0.145687)

However, in cases where comparing the keys is a nontrivial operation, the algorithm used by sort_by is considerably faster.

sort_by can also be useful for multilevel sorts. One trick, which relies on the fact that arrays are compared element by element, is to have the block return an array of each of the comparison keys. For example, to sort a list of words first on their length and then alphabetically, you could write the following:

words = %w{ puma cat bass ant aardvark gnu fish }

sorted = words.sort_by {|w| [w.length, w] }

sorted # => ["ant", "cat", "gnu", "bass", "fish", "puma", "aardvark"]

Returns an Enumerator object if no block is given.

take

  • enum.take(n ) → array

Returns an array containing the first n items from enum.

(1..7).take(3) # => [1, 2, 3]

{ 'a'=>1, 'b'=>2, 'c'=>3 }.take(2) # => [["a", 1], ["b", 2]]

take_while

  • enum.take_while { |item| … } →array or enumerator

Passes successive items to the block, adding them to the result array until the block returns false or nil. Returns an Enumerator object if no block is given.

(1..7).take_while {|item| item < 3 } # => [1, 2]

[ 2, 4, 6, 9, 11, 16 ].take_while(&:even?) # => [2, 4, 6]

to_a

  • enum.to_a(*args) →array

Returns an array containing the items in enum. This is done using the each method. Any arguments passed to to_a are passed to each.

(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]]

zip

  • enum.zip(<arg>+) → array
  • enum.zip(<arg>+) { |arr| … } → nil

Converts any arguments to arrays and then merges elements of enum with corresponding elements from each argument. The result is an array containing the same number of elements as enum. Each element is an n-element array, where n is one more than the count of arguments. If the size of any argument is less than the number of elements in enum, 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]]

[1, 2].zip([3]) # => [[1, 3], [2, nil]]

(1..3).zip # => [[1], [2], [3]]

Class Enumerator < Object

Relies on:

each, <=>

Enumerator allows you to capture the concept of an enumeration as an object. This allows you to store enumerations in variables, pass them as parameters, and so on.

You can also create enumerators with the method Object#to_enum (or via its alias, enum_for ). By default, these methods look for an each method in the object you’re enumerating, but this can be overridden by passing the name of a method (and possibly parameters to be used) that invokes a block for each item to be enumerated.

str = "quick brown fox"

case what_to_process # set elsewhere to :by_word

when :by_bytes

enum = str.to_enum(:each_byte)

when :by_word

enum = str.to_enum(:scan, /\w+/)

end

enum.each {|item| p item}

Produces:

"quick"

"brown"

"fox"

Mixes in

Enumerable

all?, any?, chunk, collect, collect_concat, count, cycle, detect, drop, drop_while, each_cons, each_entry, each_slice, each_with_index, each_with_object, entries, find, find_all, find_index, first, flat_map, grep, group_by, include?, inject, lazy, map, max, max_by, member?, min, min_by, minmax, minmax_by, none?, one?, partition, reduce, reject, reverse_each, select, slice_before, sort, sort_by, take, take_while, to_a, zip

Enumerator: Class methods

new

  • Enumerator.new(<size=nil>) { |yielder| … } → enum

Constructs an enumerator based on the block. The block is passed an object of class Enumerator::Yielder. You can use the << or yield methods of this yielder to supply values to be returned by the enumerator. This process is performed lazily (similar to the way that fibers can be used to generate sequences).

def multiples_of(n)

Enumerator.new do |yielder|

number = 0

loop do

yielder.yield number

number += n

end

end

end

twos = multiples_of(2)

threes = multiples_of(3)

5.times do

puts "#{twos.next} #{threes.next}"

end

Produces:

0 0

2 3

4 6

6 9

8 12

The optional argument specifies the value that will be returned by the size method for this enumerator. If can be nil (meaning the size cannot be determined), a number, or a proc that returns a number.«2.0»

Enumerator: Instance methods

each

  • enum.each { |item, ...| … } →obj

Calls the block for each item in the enumeration. This does not create an intermediate array. Instead, the original iterating method (the one used when creating the enumerator) is called, passing it the block passed to this method. The block receives as many parameters as the original method passes.

enum = (1..10).enum_for(:each_slice, 3)

enum.each { |item| p item }

Produces:

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

[10]

Note that because Enumerator defines each and includes Enumerable, all the enumerable methods are available too.

enum = "quick brown fox".enum_for(:scan, /\w+/)

enum.minmax # => ["brown", "quick"]

each_with_index

  • enum.each_with_index { |item, ..., index| … } →obj

Same as each but appends an index argument when calling the block. Returns a new Enumerator if no block is given.

enum = (1..10).enum_for(:each_slice, 3)

enum.each_with_index do |subarray, index|

puts "#{index}: #{subarray}"

end

Produces:

0: [1, 2, 3]

1: [4, 5, 6]

2: [7, 8, 9]

3: [10]

each_with_object

  • enum.each_with_object(memo ) { |item, memo| … } → memo or enumerator

Calls block for each item in enum, passing it the item and the parameter passed initially to each_with_object . Returns an Enumerator object if no block is given.

animals = %w(cat dog wombat).to_enum

hash = animals.each_with_object({}) do |item, memo|

memo[item] = item.upcase.reverse

end

hash # => {"cat"=>"TAC", "dog"=>"GOD", "wombat"=>"TABMOW"}

feed

  • enum.feed(obj ) → nil

In a normal looping construct, the next keyword can take an optional parameter, which is returned to the code that is controlling the iteration as the value returned by yield. enum.feed does the same thing for enumerators, setting the value returned by yield in the underlying enumerable to obj.

next

  • enum.next →obj

Returns the next item in the enumeration. Raises StopIteration if you call it past the last item. Internally this is implemented using fibers and so cannot be called across threads. See also Enumerator.next_values.

array = [ 1, 2, 3, 4 ]

e1 = array.to_enum

e2 = array.to_enum

e1.next # => 1

e1.next # => 2

e2.next # => 1

If the underlying method called by the enumerator has side effects (such as moving your position while reading a file), those side effects will be triggered. For this reason, next breaks the abstraction provided by Enumerator.

f = File.open("testfile")

enum1 = f.to_enum(:each_byte)

enum2 = f.to_enum

enum1.next # => 84

enum1.next # => 104

enum2.next # => "is is line one\n"

f.gets # => "This is line two\n"

enum2.next # => "This is line three\n"

next_values

  • enum.next_values →array

Enumerator.next returns successive values yielded by enum. However, it effectively uses raw proc semantics and so is unable to distinguish the case when the iterator yields nil and the case where the yield is passed no parameter. Similarly, it cannot distinguish yield 1,2 from yield [1,2]—both are received as [1,2]. next_values overcomes this by always returning an array, and that array contains exactly what was passed to the yield.

def each

yield 1

yield nil

yield 2, 3

yield [4,5]

end

enum = to_enum

enum.next # => 1

enum.next # => nil

enum.next # => [2, 3]

enum.next # => [4, 5]

enum = to_enum

enum.next_values # => [1]

enum.next_values # => [nil]

enum.next_values # => [2, 3]

enum.next_values # => [[4, 5]]

peek

  • enum.peek →obj

Returns the value that would be returned by calling next but does not consume that value. Raises a StopIteration exception if called past the end of enum.

enum = %w{ ant bee cat }.to_enum

enum.peek # => "ant"

enum.peek # => "ant"

enum.next # => "ant"

enum.peek # => "bee"

peek_values

  • enum.peek_values →array

Returns the value that would be returned by calling next_values .

rewind

  • enum.rewind →enum

Resets the sequence of values to be returned by next .

array = [ 1, 2, 3, 4 ]

e1 = array.to_enum

e2 = array.to_enum

e1.next # => 1

e1.next # => 2

e2.next # => 1

e1.rewind

e1.next # => 1

e2.next # => 2

Has no effect if the underlying method of the enumerator has side effects and therefore cannot be rewound.

size

  • enum.size →int or nil

Returns the size of this collection, or nil if the size cannot be calculated (this may or may not be the case with a lazy enumerator).«2.0»

File.open("/etc/passwd").to_enum.size # => nil

(1..Float::INFINITY).size # => Infinity

loop.size # => Infinity

(1..10).find.size # => nil

with_index

  • enum.with_index { |item, ..., index| … } →obj

Synonym for each_with_index .

with_object

  • enum.with_object(memo ) { |item, memo| … } → memo or enumerator

Synonym for each_with_object .

Module Errno

Ruby exception objects are subclasses of Exception. However, operating systems typically report errors using plain integers. Module Errno is created dynamically to map these operating system errors to Ruby classes, with each error number generating its own subclass of SystemCallError. Because the subclass is created in module Errno, its name will start Errno::.

Exception

StandardError

SystemCallError

Errno::XXX

The names of the Errno:: classes depend on the environment in which Ruby runs. On a typical Unix or Windows platform, you’ll find Ruby has Errno classes such as Errno::EACCES, Errno::EAGAIN, Errno::EINTR, and so on.

The integer operating system error number corresponding to a particular error is available as the class constant Errno::error::Errno.

Errno::EACCES::Errno # => 13

Errno::EAGAIN::Errno # => 35

Errno::EINTR::Errno # => 4

The full list of operating system errors on your particular platform is available as the constants of Errno. Any user-defined exceptions in this module (including subclasses of existing exceptions) must also define an Errno constant.

Errno.constants[0..4] # => [:NOERROR, :EPERM, :ENOENT, :ESRCH, :EINTR]

As of Ruby 1.8, exceptions are matched in rescue clauses using Module#===. The === method is overridden for class SystemCallError to compare based on the Errno value. Thus, if two distinct Errno classes have the same underlying Errno value, they will be treated as the same exception by a rescue clause.

Class Exception < Object

Descendents of class Exception are used to communicate between raise methods and rescue statements in begin/end blocks. Exception objects carry information about the exception—its type (the exception’s class name), an optional descriptive string, and optional traceback information.

The standard library defines the exceptions shown in Figure 1, Standard exception hierarchy. Note that Ruby 1.9 has changed the hierarchy slightly. In particular, SecurityError is no longer a subclass of StandardError and so will not be rescued implicitly.

See also the description of Errno.

Exception: Class methods

exception

  • Exception.exception(<message> ) → exc

Creates and returns a new exception object, optionally setting the message to message.

new

  • Exception.new(<message> ) → exc

Creates and returns a new exception object, optionally setting the message to message.

Exception: Instance methods

==

  • exc== other → true or false

Returns true only if other shares the same message and backtrace as exc.

backtrace

  • exc.backtrace →array

Returns any backtrace associated with the exception. The backtrace is an array of strings, each containing either filename:line: in ‘method’ or filename:line.

def a

raise "boom"

end

def b

a()

end

begin

b()

rescue => detail

print detail.backtrace.join("\n")

end

Produces:

prog.rb:2:in `a'

prog.rb:5:in `b'

prog.rb:8:in `<main>'

exception

  • exc.exception(<message> ) → exc or exception

With no argument, returns the receiver. Otherwise, creates a new exception object of the same class as the receiver but with a different message.

message

  • exc.message →msg

Returns the message associated with this exception.

set_backtrace

  • exc.set_backtrace(array ) → array

Sets the backtrace information associated with exc. The argument must be an array of String objects in the format described in Exception#backtrace.

status

  • exc.status → status

(SystemExit only.) Returns the exit status associated with this SystemExit exception. Normally this status is set using the Object#exit.

begin

exit(99)

rescue SystemExit => e

puts "Exit status is: #{e.status}"

end

Produces:

Exit status is: 99

success?

  • exc.success? → true or false

(SystemExit only.) Returns true if the exit status is nil or zero.

begin

exit(99)

rescue SystemExit => e

print "This program "

if e.success?

print "did"

else

print "did not"

end

puts " succeed"

end

Produces:

This program did not succeed

to_s

  • exc.to_s →msg

Returns the message associated with this exception (or the name of the exception if no message is set).

begin

raise "The message"

rescue Exception => e

puts e.to_s

# This is the same as the previous puts

puts e

end

Produces:

The message

The message

Class FalseClass < Object

The global value false is the only instance of class FalseClass and represents a logically false value in boolean expressions. The class provides operators allowing false to participate correctly in logical expressions.

FalseClass: Instance methods

&

  • false &obj → false

And—Returns false. obj is always evaluated because it is the argument to a method call—no short-circuit evaluation is performed in this case. In other words, the following code, which uses &&, will not invoke the lookup method.

def lookup(val)

puts "Looking up #{val}"

return true

end

false && lookup("cat")

However, this code, using &, will:

false & lookup("cat")

Produces:

Looking up cat

^

  • false ^objtrue or false

Exclusive Or—If obj is nil or false, returns false; otherwise, returns true.

|

  • false |objtrue or false

Or—Returns false if obj is nil or false; true otherwise.

Class Fiber < Object

A fiber is a lightweight asymetrical coroutine. Code in a fiber is created in a suspended state. It runs when resumed and can suspend itself (passing a value back to the code that resumed it). There is a full description of fibers in Section 12.1, Fibers.

fibonaccis = Fiber.new do

n1 = n2 = 1

loop do

Fiber.yield n1

n1, n2 = n2, n1+n2

end

end

10.times { print fibonaccis.resume, ' ' }

Produces:

1 1 2 3 5 8 13 21 34 55

Fiber: Class methods

new

  • Fiber.new { … } →fiber

Uses the block as a new, suspended fiber.

yield

  • Fiber.yield(<val>* ) → obj

Suspends execution of the current fiber. Any parameters will be returned as the value of the resume call that awoke the fiber. Similarly, any values passed to resume will become the return value of the subsequent yield .

f = Fiber.new do |first|

print first

letter = "A"

loop do

print Fiber.yield(letter)

letter = letter.succ

end

end

10.times { |number| print f.resume(number) }

Produces:

0A1B2C3D4E5F6G7H8I9J

Fiber: Instance methods

resume

  • fiber.resume(<val>* ) → obj

Resumes fiber. See Fiber.yield for a discussion and example of parameter passing. It is an error to resume a fiber that is being used as a coroutine (one that calls transfer ). See Fiber.«2.0»

Class File < IO

A File is an abstraction of any file object accessible by the program and is closely associated with class IO, described later. File includes the methods of module FileTest as class methods, allowing you to write (for example) File.exist?("foo").

Files may be opened in binary mode (where the contents are transferred as 8-bit bytes in binary encoding) or text mode (where the contents are interpreted as codepoints in a particular encoding). These options are controlled by the mode parameter when a file is opened.

Each file has three associated times: atime is the time the file was last accessed, ctime is the time that the file status (not necessarily the file contents) were last changed, and mtime is the time the file’s data was last modified. In Ruby, all these times are returned as Time objects.

In this section, permission bits are a platform-specific set of bits that indicate permissions of a file. On Unix-based systems, permissions are viewed as a set of three octets, for the owner, the group, and the rest of the world. For each of these entities, permissions may be set to read, write, or execute the file.

Owner

Group

Other

r

w

x

r

w

x

r

w

x

400

200

100

40

20

10

4

2

1

The permission bits 0644 (in octal) would thus be interpreted as read/write for owner and read-only for group and other. Higher-order bits may also be used to indicate the type of file (plain, directory, pipe, socket, and so on) and various other special features. If the permissions are for a directory, the meaning of the execute bit changes; when set, the directory can be searched.

Non-POSIX operating systems may not support the full set of possible permissions. In this case, the remaining permission bits will be synthesized to resemble typical values. For instance, on Windows the default permission bits are 0644, which means read/write for owner and read-only for all others. The only change that can be made is to make the file read-only, which is reported as 0444.

The constant File::NULL is the name of your system’s null device. Reading from it returns end-of-file, and writing to it is ignored.

See also Pathname and IO.

File: Class methods

absolute_path

  • File.absolute_path(filename <, dirstring> ) → filename

Converts a path to an absolute path. Relative paths are referenced from the current working directory of the process unless dirstring is given, in which case it will be used as the starting point. Path names starting with ~ are not expanded, in contrast with File#expand_path.

puts File.absolute_path("bin")

puts File.absolute_path("../../bin", "/tmp/x")

Produces:

/Users/dave/BS2/published/ruby4/Book/bin

/bin

atime

  • File.atime(filename ) → time

Returns a Time object containing the last access time for the named file or returns epoch if the file has not been accessed.

File.atime("testfile") # => 2013-05-27 12:32:02 -0500

basename

  • File.basename(filename <, suffix> ) → string

Returns the last component of the filename given in filename. If suffix is given and is present at the end of filename, it is removed. Any extension can be removed by giving an extension of .*.

File.basename("/home/gumby/work/ruby.rb") # => "ruby.rb"

File.basename("/home/gumby/work/ruby.rb", ".rb") # => "ruby"

File.basename("/home/gumby/work/ruby.rb", ".*") # => "ruby"

blockdev?

  • File.blockdev?(filename ) → true or false

Returns true if the named file is a block device and returns false if it isn’t or if the operating system doesn’t support this feature.

File.blockdev?("testfile") # => false

chardev?

  • File.chardev?(filename ) → true or false

Returns true if the named file is a character device and returns false if it isn’t or if the operating system doesn’t support this feature.

File.chardev?("/dev/tty") # => true

chmod

  • File.chmod(permission <, filename>+ ) → int

Changes permission bits on the named file(s) to the bit pattern represented by permission. Actual effects are operating system dependent (see the beginning of this section). On Unix systems, see chmod(2) for details. Returns the number of files processed.

File.chmod(0644, "testfile", "some_other_file") # => 2

chown

  • File.chown(owner, group <, filename>+ ) → int

Changes the owner and/or group of the named file(s) to the given numeric owner and group IDs. 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")

ctime

  • File.ctime(filename ) → time

Returns a Time object containing the time that the file status associated with the named file was changed.

File.ctime("testfile") # => 2013-05-27 12:32:04 -0500

delete

  • File.delete(<filename>+ ) → int

Deletes the named file(s). Returns the number of files processed. See also Dir.rmdir.

File.open("testrm", "w+") {}

File.delete("testrm") # => 1

directory?

  • File.directory?(path ) → true or false

Returns true if the named file is a directory; returns false otherwise.

File.directory?(".") # => true

dirname

  • File.dirname(filename ) → filename

Returns all components of the filename given in filename except the last one.

File.dirname("/home/gumby/work/ruby.rb") # => "/home/gumby/work"

File.dirname("ruby.rb") # => "."

executable?

  • File.executable?(filename ) → true or false

Returns true if the named file is executable. The tests are made using the effective owner of the process.

File.executable?("testfile") # => false

executable_real?

  • File.executable_real?(filename ) → true or false

Same as File#executable? but tests using the real owner of the process.

exist?

  • File.exist?(filename ) → true or false

Returns true if the named file or directory exists.

File.exist?("testfile") # => true

exists?

  • File.exists? (filename ) → true or false

Synonym for File.exist?.

expand_path

  • File.expand_path(filename <, dirstring> ) → filename

Converts a path name to an absolute path name. Relative paths are referenced from the current working directory of the process unless dirstring is given, in which case it will be used as the starting point. The given path name 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. See also File#absolute_path.

File.expand_path("~/bin") # => "/Users/dave/bin"

File.expand_path("../../bin", "/tmp/x") # => "/bin"

extname

  • File.extname(path ) → string

Returns the extension (the portion of filename in path after the period).

File.extname("test.rb") # => ".rb"

File.extname("a/b/d/test.rb") # => ".rb"

File.extname("test") # => ""

file?

  • File.file?(filename ) → true or false

Returns true if the named file is a regular file (not a device file, directory, pipe, socket, and so on).

File.file?("testfile") # => true

File.file?(".") # => false

fnmatch

  • File.fnmatch(glob_pattern, path, <flags> ) → true or false

Returns true if path matches against glob_pattern. The pattern is not a regular expression; instead, it follows rules similar to shell filename globbing. A glob_pattern may contain the following metacharacters.

*

Matches zero or more characters in a file or directory name.

**

Matches zero or more characters, ignoring name boundaries. Most often used to scan subdirectories recursively.

?

Matches any single character.

[ charset ]

Matches any character from the given set of characters. A range of characters is written as from-to. The set may be negated with an initial caret (^).

\

Escapes any special meaning of the next character.

flags is a bitwise OR of the FNM_xxx constants.

FNM_EXTGLOB

Expand braces in the pattern.«2.0»

FNM_NOESCAPE

A backslash does not escape special characters in globs, and a backslash in the pattern must match a backslash in the filename.

FNM_PATHNAME

Forward slashes in the filename are treated as separating parts of a path and so must be explicitly matched in the pattern.

FNM_DOTMATCH

If this option is not specified, filenames containing leading periods must be matched by an explicit period in the pattern. A leading period is one at the start of the filename or (if FNM_PATHNAME is specified) following a slash.

FNM_CASEFOLD

Filename matches are case insensitive.

See also Dir.glob.

File.fnmatch('cat', 'cat') # => true

File.fnmatch('cat', 'category') # => 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/**/t', 'c/a/b/c/t') # => true

File.fnmatch('c**t', 'c/a/b/c/t') # => true

File.fnmatch('c**t', 'cat') # => true

File.fnmatch('**.txt', 'some/dir/tree/notes.txt') # => 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('*/*', 'dave/.profile', File::FNM_PATHNAME) # => false

STRICT = File::FNM_PATHNAME | File::FNM_DOTMATCH

File.fnmatch('*/*', 'dave/.profile', STRICT) # => true

fnmatch?

  • File.fnmatch?(glob_pattern, path, <flags> ) → (true or false)

Synonym for File#fnmatch.

ftype

  • File.ftype(filename ) → filetype

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"

system("mkfifo wibble") # => true

File.ftype("wibble") # => "fifo"

grpowned?

  • File.grpowned?(filename ) → true or false

Returns true if the effective group ID of the process is the same as the group ID of the named file. On Windows, returns false.

File.grpowned?("/etc/passwd") # => false

identical?

  • File.identical?(name1, name2 ) → true or false

Returns true only if name1 and name2 refer to the same file. Two separate files with the same content are not considered to be identical.

File.identical?("testfile", "./code/../testfile") # => true

File.symlink("testfile", "wibble")

File.identical?("testfile", "wibble") # => true

File.link("testfile", "wobble")

File.identical?("testfile", "wobble") # => true

File.identical?("wibble", "wobble") # => true

join

  • File.join(<string>+ ) → filename

Returns a new string formed by joining the strings using File::SEPARATOR. The various separators are as follows:

ALT_SEPARATOR

Alternate path separator (\ on Windows, nil otherwise)

PATH_SEPARATOR

Separator for filenames in a search path (such as : or ;)

SEPARATOR

Separator for directory components in a filename (such as \ or /)

Separator

Alias for SEPARATOR

File.join("usr", "mail", "gumby") # => "usr/mail/gumby"

lchmod

  • File.lchmod(permission, <filename>+ ) → 0

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.

lchown

  • File.lchown(owner, group, <filename>+ ) → 0

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.

link

  • File.link(oldname, newname ) → 0

Creates a new name for an existing file using a hard link. Will not overwrite newname if it already exists (in which case link raises a subclass of SystemCallError). Not available on all platforms.

File.link("testfile", "testfile.2") # => 0

f = File.open("testfile.2")

f.gets # => "This is line one\n"

File.delete("testfile.2")

lstat

  • File.lstat(filename ) → stat

Returns status information for file as an object of type File::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

File.lstat("link2test").size # => 8

File.stat("link2test").size # => 66

mtime

  • File.mtime(filename ) → time

Returns a Time object containing the modification time for the named file.

File.mtime("testfile") # => 2013-05-16 20:00:29 -0500

File.mtime("/tmp") # => 2013-05-27 11:52:10 -0500

new

  • File.new(filename, mode="r" <, permission> <options> ) → file
  • File.new(integer_fd <, mode options> ) → file

If the first parameter is an integer (or can be converted to an integer using to_int ), it is the file descriptor or an already-open file. In that case, the call is passed to IO.new for processing.

More commonly, opens the file named by filename according to mode (the default is "r") and returns a new File object. The mode contains information on the way the file is to be opened and optionally on the encodings to be associated with the file data. Modes are most commonly represented as a string but can be expressed as an integer. Mode strings have the form file-mode[:external-encoding[:internal-encoding]]". The file-mode portion is one of the options listed in the following table. The two encodings are the names (or aliases) of encodings supported by your interpreter. See Chapter 17, Character Encoding for more information.

Table 16. Mode values

r

Read-only, starts at beginning of file (default mode).

r+

Read/write, starts at beginning of file.

w

Write-only, truncates an 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

Binary file mode (may appear with any of the key letters listed earlier). As of Ruby 1.9, this modifier should be supplied on all ports opened in binary mode (on Unix as well as on DOS/Windows). To read a file in binary mode and receive the data as a stream of bytes, use the modestring "rb:ascii-8bit".

When expressed as an integer, the mode is specified by OR-ing together the values in the following table. If your system does not support the underlying functionality, the constants will not be defined. The descriptions below are just hints at the underlying functionality—see the man page for open(2) for the details.

File::APPEND

Opens the file in append mode; all writes will occur at end of file.

File::ASYNC

Generate a signal when input or output become possible.

File::BINARY

Use Ruby’s binary mode.

File::CREAT

Creates the file on open if it does not exist.

File::DIRECT

Try to minimize the effects of caching.

File::DSYNC

Opens for synchronous I/O, blocking until buffered data (but not necessarily inode information) is written.

File::EXCL

When used with File::CREAT, opens will fail if the file exists.

File::NOATIME

Do not update the file’s last access time on reading.

File::NOCTTY

When opening a terminal device (see IO#isatty), does not allow it to become the controlling terminal.

File::NOFOLLOW

Do not open the file if the name is a symbolic link.

File::NONBLOCK

Opens the file in nonblocking mode.

File::RDONLY

Opens for reading only.

File::RDWR

Opens for reading and writing.

File::SYNC

Opens for synchronous I/O, blocking until buffered data is written.

File::TRUNC

Opens the file and truncates it to zero length if the file exists.

File::WRONLY

Opens for writing only.

Optional permission bits may be given in permission. These bits are platform dependent; on Unix systems, see open(2) for details.

If the final parameter is a hash, it is used to control options, as described in the following table. The mode can be passed as one of the options of this hash.

Table 17. File and I/O open options

autoclose:

If false, the underlying file will not be closed when this I/O object is finalized.

binmode:

Opens the IO object in binary mode if true (same as mode: "b").

encoding:

Specifies both external and internal encodings as "external:internal" (same format used in mode parameter.

external_encoding:

Specifies the external encoding.

internal_encoding:

Specifies the internal encoding.

mode:

Specifies what would have been the mode parameter (so File.open("xx", "r:utf-8") is the same as File.open("xx", mode: "r:utf-8").

perm:

Specifies what would have been the permission parameter.

textmode:

Open the file in text mode (the default).

In addition, the options parameter can use the key/value pairs that are specified to String.encode to control the processing of text data. See Table 22, Options to encode and encode!.

See also IO.open for a block form of File.new.

# open for reading, default external encoding

f = File.new("testfile", "r")

# open for reading, assume contents are utf-8

f = File.new("testfile", "r:utf-8")

# Same, using an options hash

f = File.new("testfile", mode: "r", external_encoding: "utf-8")

# Translate cr/lf to just lf (a String#encode option)

f = File.new("testfile", universal_newline: true)

# open for read/write. external utf-8 data will be converted to iso-8859-1

# when read, and converted from 8859-1 to utf-8 on writing

f = File.new("newfile", "w+:utf-8:iso-8859-1")

# same as specifying "w+"

f = File.new("newfile", File::CREAT|File::TRUNC|File::RDWR, 0644)

owned?

  • File.owned?(filename ) → true or false

Returns true if the effective user ID of the process is the same as the owner of the named file.

File.owned?("/etc/passwd") # => false

path

  • File.path(obj ) → string

Returns the path of obj. If obj responds to to_path , its value is returned. Otherwise, attempt to convert obj to a string and return that value.

File.path("testfile") # => "testfile"

File.path("/tmp/../tmp/xxx") # => "/tmp/../tmp/xxx"

f = File.open("/tmp/../tmp/xxx")

File.path(f) # => "/tmp/../tmp/xxx"

pipe?

  • File.pipe?(filename ) → true or false

Returns true if the OS supports pipes and the named file is one; false otherwise.

File.pipe?("testfile") # => false

readable?

  • File.readable?(filename ) → true or false

Returns true if the named file is readable by the effective user ID of this process.

File.readable?("testfile") # => true

readable_real?

  • File.readable_real?(filename ) → true or false

Returns true if the named file is readable by the real user ID of this process.

File.readable_real?("testfile") # => true

readlink

  • File.readlink(filename ) → filename

Returns the given symbolic link as a string. Not available on all platforms.

File.symlink("testfile", "link2test") # => 0

File.readlink("link2test") # => "testfile"

realdirpath

  • File.realdirpath(path <, relative_to>) → string

Converts path to a full file path, with all symlinks resolved and relative paths made absolute. If a second parameter if present, it is used as the base for resolving leading relative path segments. The actual file (the past component of the path) need not exist.

puts File.realdirpath("/var/log/system.log")

puts File.realdirpath("../Common/xml")

puts File.realdirpath("Sites", "/Users/dave")

Produces:

/private/var/log/system.log

/Users/dave/BS2/published/ruby4/Common/xml

/Users/dave/Sites

realpath

  • File.realpath(path <, relative_to>) → string

Converts path to a full file path, with all symlinks resolved and relative paths made absolute. If a second parameter if present, it is used as the base for resolving leading relative path segments.

puts File.realpath("/var/log/system.log")

puts File.realpath("../PerBook/util/xml/ppbook.dtd")

puts File.realpath("Sites/index.html", "/Users/dave")

Produces:

/private/var/log/system.log

/Users/dave/BS2/published/ruby4/PerBook/util/xml/ppbook.dtd

/Users/dave/Sites/index.html

rename

  • File.rename(oldname, newname ) → 0

Renames the given file or directory to the new name. Raises a SystemCallError if the file cannot be renamed.

File.rename("afile", "afile.bak") # => 0

setgid?

  • File.setgid?(filename ) → true or false

Returns true if the named file’s set-group-id permission bit is set and returns false if it isn’t or if the operating system doesn’t support this feature.

File.setgid?("/usr/sbin/lpc") # => false

setuid?

  • File.setuid?(filename ) → true or false

Returns true if the named file’s set-user-id permission bit is set and returns false if it isn’t or if the operating system doesn’t support this feature.

File.setuid?("/bin/su") # => false

size

  • File.size(filename ) → int

Returns the size of the file in bytes.

File.size("testfile") # => 66

size?

  • File.size?(filename ) → int or nil

Returns nil if the named file is of zero length; otherwise, returns the size. Usable as a condition in tests.

File.size?("testfile") # => 66

File.size?("/dev/zero") # => nil

socket?

  • File.socket?(filename ) → true or false

Returns true if the named file is a socket and returns false if it isn’t or if the operating system doesn’t support this feature.

split

  • File.split(filename ) → array

Splits the given string into a directory and a file component and returns them in a two-element array. See also File.dirname and File.basename.

File.split("/home/gumby/.profile") # => ["/home/gumby", ".profile"]

File.split("ruby.rb") # => [".", "ruby.rb"]

stat

  • File.stat(filename ) → stat

Returns a File::Stat object for the named file (see File::Stat).

stat = File.stat("testfile")

stat.mtime # => 2013-05-16 20:00:29 -0500

stat.ftype # => "file"

sticky?

  • File.sticky?(filename ) → true or false

Returns true if the named file has its sticky bit set and returns false if it doesn’t or if the operating system doesn’t support this feature.

symlink

  • File.symlink(oldname, newname ) → 0 or nil

Creates a symbolic link called newname for the file oldname. Returns nil on all platforms that do not support symbolic links.

File.symlink("testfile", "link2test") # => 0

symlink?

  • File.symlink?(filename ) → true or false

Returns true if the named file is a symbolic link and returns false if it isn’t or if the operating system doesn’t support this feature.

File.symlink("testfile", "link2test") # => 0

File.symlink?("link2test") # => true

truncate

  • File.truncate(filename, int ) → 0

Truncates the file filename to be at most int 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

umask

  • File.umask(<int> ) → int

Returns the current umask value for this process. If the optional argument is given, sets the umask to that value and returns the previous value. Umask values are excluded from the default permissions; so, a umask of 0222 would make a file read-only for everyone. See also the discussion of permissions.

File.umask(0006) # => 18

File.umask # => 6

unlink

  • File.unlink(<filename>+ ) → int

Synonym for File.delete. See also Dir.rmdir.

File.open("testrm", "w+") {} # => nil

File.unlink("testrm") # => 1

utime

  • File.utime(accesstime, modtime <, filename>+ ) → int

Changes the access and modification times on a number of files. The times must be instances of class Time or integers representing the number of seconds since epoch. Returns the number of files processed. Not available on all platforms.

File.utime(0, 0, "testfile") # => 1

File.mtime("testfile") # => 1969-12-31 18:00:00 -0600

File.utime(0, Time.now, "testfile") # => 1

File.mtime("testfile") # => 2013-05-27 12:32:07 -0500

world_readable?

  • File.world_readable?(filename ) → perm_int or nil

If filename is readable by others, returns an integer representing the file permission bits of filename. Returns nil otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2).

File.world_readable?("/etc/passwd") # => 420

File.world_readable?("/etc/passwd").to_s(8) # => "644"

world_writable?

  • File.world_writable?(filename ) → perm_int or nil

If filename is writable by others, returns an integer representing the file permission bits of filename. Returns nil otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2).

File.world_writable?("/etc/passwd") # => nil

File.world_writable?("/tmp") # => 511

File.world_writable?("/tmp").to_s(8) # => "777"

writable?

  • File.writable?(filename ) → true or false

Returns true if the named file is writable by the effective user ID of this process.

File.writable?("/etc/passwd") # => false

File.writable?("testfile") # => true

writable_real?

  • File.writable_real?(filename ) → true or false

Returns true if the named file is writable by the real user ID of this process.

zero?

  • File.zero?(filename ) → true or false

Returns true if the named file is of zero length and returns false otherwise.

File.zero?("testfile") # => false

File.open("zerosize", "w") {}

File.zero?("zerosize") # => true

File: Instance methods

atime

  • file.atime →time

Returns a Time object containing the last access time for file or returns epoch if the file has not been accessed.

File.new("testfile").atime # => 1969-12-31 18:00:00 -0600

chmod

  • file.chmod(permission ) → 0

Changes permission bits on file to the bit pattern represented by permission. Actual effects are platform dependent; on Unix systems, see chmod(2) for details. Follows symbolic links. See the discussion of permissions. Also see File.lchmod.

f = File.new("out", "w");

f.chmod(0644) # => 0

chown

  • file.chown(owner, group ) → 0

Changes the owner and group of file to the given numeric owner and group IDs. 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, 400)

ctime

  • file.ctime →time

Returns a Time object containing the time that the file status associated with file was changed.

File.new("testfile").ctime # => 2013-05-27 12:32:07 -0500

flock

  • file.flock (locking_constant ) → 0 or false

Locks or unlocks a file according to locking_constant (a logical or of the following values).

Table 18. Lock-mode constants

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 | (or)

LOCK_SH

Shared lock. Multiple processes may each hold a shared lock for a given file at the same time.

LOCK_UN

Unlock.

Returns false if File::LOCK_NB is specified, and the operation would otherwise have blocked. Not available on all platforms.

File.new("testfile").flock(File::LOCK_UN) # => 0

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

mtime

  • file.mtime →time

Returns a Time object containing the modification time for file.

File.new("testfile").mtime # => 2013-05-27 12:32:07 -0500

path

  • file.path →filename

Returns the path name 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"

size

  • file.size(filename ) → int

Returns the size of file in bytes.

File.open("testfile").size # => 66

to_path

  • file.to_path →filename

Alias for File#path.

truncate

  • file.truncate(int ) → 0

Truncates file to at most int 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

Class File::Stat < Object

Objects of class File::Stat encapsulate common status information for File objects. The information is recorded at the moment the File::Stat object is created; changes made to the file after that point will not be reflected. File::Stat objects are returned by IO#stat, File.stat, File#lstat, and File.lstat. Many of these methods may return platform-specific values, and not all values are meaningful on all systems. See also Object#test.

Mixes in

Comparable

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

File::Stat: Instance methods

<=>

  • statfile<=> other_stat → -1, 0, 1

Compares File::Stat objects by comparing their respective modification times.

f1 = File.new("f1", "w")

sleep 1

f2 = File.new("f2", "w")

f1.stat <=> f2.stat # => -1

# Methods in Comparable are also available

f1.stat > f2.stat # => false

f1.stat < f2.stat # => true

atime

  • statfile.atime →time

Returns a Time object containing the last access time for statfile or returns epoch if the file has not been accessed.

File.stat("testfile").atime # => 1969-12-31 18:00:00 -0600

File.stat("testfile").atime.to_i # => 0

blksize

  • statfile.blksize →int

Returns the native file system’s block size. Will return nil on platforms that don’t support this information.

File.stat("testfile").blksize # => 4096

blockdev?

  • statfile.blockdev? → true or false

Returns true if the file is a block device and returns false if it isn’t or if the operating system doesn’t support this feature.

File.stat("testfile").blockdev? # => false

File.stat("/dev/disk0").blockdev? # => true

blocks

  • statfile.blocks →int

Returns the number of native file system blocks allocated for this file or returns nil if the operating system doesn’t support this feature.

File.stat("testfile").blocks # => 8

chardev?

  • statfile.chardev? → true or false

Returns true if the file is a character device and returns false if it isn’t or if the operating system doesn’t support this feature.

File.stat("/dev/tty").chardev? # => true

File.stat("testfile").chardev? # => false

ctime

  • statfile.ctime →time

Returns a Time object set to the time that the file status associated with statfile was changed.

File.stat("testfile").ctime # => 2013-05-27 12:32:07 -0500

dev

  • statfile.dev →int

Returns an integer representing the device on which statfile resides. The bits in the device integer will often encode major and minor device information.

File.stat("testfile").dev # => 16777219

"%x" % File.stat("testfile").dev # => "1000003"

dev_major

  • statfile.dev_major →int

Returns the major part of File::Stat#dev or nil if the operating system doesn’t support this feature.

File.stat("testfile").dev_major # => 1

dev_minor

  • statfile.dev_minor →int

Returns the minor part of File::Stat#dev or nil if the operating system doesn’t support this feature.

File.stat("testfile").dev_minor # => 3

directory?

  • statfile.directory? → true or false

Returns true if statfile is a directory and returns false otherwise.

File.stat("testfile").directory? # => false

File.stat(".").directory? # => true

executable?

  • statfile.executable? → true or false

Returns true if statfile is executable or if the operating system doesn’t distinguish executable files from nonexecutable files. The tests are made using the effective owner of the process.

File.stat("testfile").executable? # => false

executable_real?

  • statfile.executable_real? → true or false

Same as executable? but tests using the real owner of the process.

file?

  • statfile.file? → true or false

Returns true if statfile is a regular file (not a device file, pipe, socket, and so on).

File.stat("testfile").file? # => true

ftype

  • statfile.ftype →type_string

Identifies the type of statfile. The return string is one of the following: file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown.

File.stat("/dev/tty").ftype # => "characterSpecial"

gid

  • statfile.gid →int

Returns the numeric group ID of the owner of statfile.

File.stat("testfile").gid # => 20

grpowned?

  • statfile.grpowned? → true or false

Returns true if the effective group ID of the process is the same as the group ID of statfile. On Windows, returns false.

File.stat("testfile").grpowned? # => true

File.stat("/etc/passwd").grpowned? # => false

ino

  • statfile.ino →int

Returns the inode number for statfile.

File.stat("testfile").ino # => 29399443

mode

  • statfile.mode →int

Returns an integer representing the permission bits of statfile. The meaning of the bits is platform dependent; on Unix systems, see stat(2).

File.chmod(0644, "testfile") # => 1

File.stat("testfile").mode.to_s(8) # => "100644"

mtime

  • statfile.mtime →time

Returns a Time object containing the modification time for statfile.

File.stat("testfile").mtime # => 2013-05-27 12:32:07 -0500

nlink

  • statfile.nlink →int

Returns the number of hard links to statfile.

File.stat("testfile").nlink # => 1

File.link("testfile", "testfile.bak") # => 0

File.stat("testfile").nlink # => 2

owned?

  • statfile.owned? → true or false

Returns true if the effective user ID of the process is the same as the owner of statfile.

File.stat("testfile").owned? # => true

File.stat("/etc/passwd").owned? # => false

pipe?

  • statfile.pipe? → true or false

Returns true if the operating system supports pipes and statfile is a pipe.

rdev

  • statfile.rdev →int

Returns an integer representing the device type on which statfile (which should be a special file) resides. Returns nil if the operating system doesn’t support this feature.

File.stat("/dev/disk0s1").rdev # => 16777217

File.stat("/dev/tty").rdev # => 33554432

rdev_major

  • statfile.rdev_major →int

Returns the major part of File::Stat#rdev or nil if the operating system doesn’t support this feature.

File.stat("/dev/disk0s1").rdev_major # => 1

File.stat("/dev/tty").rdev_major # => 2

rdev_minor

  • statfile.rdev_minor →int

Returns the minor part of File::Stat#rdev or nil if the operating system doesn’t support this feature.

File.stat("/dev/disk0s1").rdev_minor # => 1

File.stat("/dev/tty").rdev_minor # => 0

readable?

  • statfile.readable? → true or false

Returns true if statfile is readable by the effective user ID of this process.

File.stat("testfile").readable? # => true

readable_real?

  • statfile.readable_real? → true or false

Returns true if statfile is readable by the real user ID of this process.

File.stat("testfile").readable_real? # => true

File.stat("/etc/passwd").readable_real? # => true

setgid?

  • statfile.setgid? → true or false

Returns true if statfile has the set-group-id permission bit set and returns false if it doesn’t or if the operating system doesn’t support this feature.

File.stat("testfile").setgid? # => false

File.stat("/usr/sbin/postdrop").setgid? # => true

setuid?

  • statfile.setuid? → true or false

Returns true if statfile has the set-user-id permission bit set and returns false if it doesn’t or if the operating system doesn’t support this feature.

File.stat("testfile").setuid? # => false

File.stat("/usr/bin/su").setuid? # => true

size

  • statfile.size →int

Returns the size of statfile in bytes.

File.stat("/dev/zero").size # => 0

File.stat("testfile").size # => 66

size?

  • statfile.size? →int or nil

Returns nil if statfile is a zero-length file; otherwise, returns the file size. Usable as a condition in tests.

File.stat("/dev/zero").size? # => nil

File.stat("testfile").size? # => 66

socket?

  • statfile.socket? → true or false

Returns true if statfile is a socket and returns false if it isn’t or if the operating system doesn’t support this feature.

File.stat("testfile").socket? # => false

sticky?

  • statfile.sticky? → true or false

Returns true if statfile has its sticky bit set and returns false if it doesn’t or if the operating system doesn’t support this feature.

File.stat("testfile").sticky? # => false

symlink?

  • statfile.symlink? → true or false

Returns true if statfile is a symbolic link; returns false if it isn’t or if the operating system doesn’t support this feature. Because File.stat automatically follows symbolic links, symlink? will always be false for an object returned by File.stat.

File.symlink("testfile", "alink") # => 0

File.stat("alink").symlink? # => false

File.lstat("alink").symlink? # => true

uid

  • statfile.uid →int

Returns the numeric user ID of the owner of statfile.

File.stat("testfile").uid # => 501

world_readable?

  • statfile.world_readable?(filename ) → perm_int or nil

If filename is readable by others, returns an integer representing the file permission bits of filename. Returns nil otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2).

File.stat("/etc/passwd").world_readable? # => 420

File.stat("/etc/passwd").world_readable?.to_s(8) # => "644"

world_writable?

  • statfile.world_writable?(filename ) → perm_int or nil

If filename is writable by others, returns an integer representing the file permission bits of filename. Returns nil otherwise. The meaning of the bits is platform dependent; on Unix systems, see stat(2).

File.stat("/etc/passwd").world_writable? # => nil

File.stat("/tmp").world_writable? # => 511

File.stat("/tmp").world_writable?.to_s(8) # => "777"

writable?

  • statfile.writable? → true or false

Returns true if statfile is writable by the effective user ID of this process.

File.stat("testfile").writable? # => true

writable_real?

  • statfile.writable_real? → true or false

Returns true if statfile is writable by the real user ID of this process.

File.stat("testfile").writable_real? # => true

zero?

  • statfile.zero? → true or false

Returns true if statfile is a zero-length file; returns false otherwise.

File.stat("testfile").zero? # => false

Module FileTest

FileTest implements file test operations similar to those used in File::Stat. The methods in FileTest are duplicated in class File. Rather than repeat the documentation here, we list the names of the methods and refer you to the documentation for File. FileTest appears to be a somewhat vestigial module.

The FileTest methods are: blockdev? , chardev? , directory? , executable? , executable_real? , exist? , exists? , file? , grpowned? , identical? , owned? , pipe? , readable? , readable_real? , setgid? , setuid? , size , size? , socket? , sticky? , symlink? , world_readable? , world_writable? , writable? , writable_real? , zero?

Class Fixnum < Integer

A Fixnum holds integer values that can be represented in a native machine word (minus 1 bit). If any operation on a Fixnum exceeds this range, the value is converted to a Bignum.

Fixnum objects have immediate value. This means that when they are assigned or passed as parameters, the actual object is passed, rather than a reference to that object. Assignment does not alias Fixnum objects. Because there is effectively only one Fixnum object instance for any given integer value, you cannot, for example, add a singleton method to a Fixnum.

Fixnum: Instance methods

Arithmetic operations

Performs various arithmetic operations on fix.

fix

+

numeric

Addition

fix

--

numeric

Subtraction

fix

*

numeric

Multiplication

fix

/

numeric

Division

fix

%

numeric

Modulo

fix

**

numeric

Exponentiation

fix

-@

Unary minus

Bit operations

Performs various operations on the binary representations of the Fixnum.

~ fix

Invert bits

fix

|

numeric

Bitwise or

fix

&

numeric

Bitwise and

fix

^

numeric

Bitwise exclusive or

fix

<<

numeric

Left-shift numeric bits

fix

>>

numeric

Right-shift numeric bits (with sign extension)

Comparisons

Compares fix to other numbers. Fixnum. < , <= , == , >= , and > .

<=>

  • fix<=> numeric → -1, 0, +1, or nil

Comparison—Returns -1, 0, or +1 depending on whether fix is less than, equal to, or greater than numeric. Although Fixnum’s grandparent mixes in Comparable, Fixnum does not use that module for performing comparisons, instead implementing the comparison operators explicitly.

42 <=> 13 # => 1

13 <=> 42 # => -1

-1 <=> -1 # => 0

[ ]

  • fix[n ] → 0, 1

Bit Reference—Returns the nth bit in the binary representation of fix, where fix[0] is the least significant bit.

a = 0b11001100101010

30.downto(0) {|n| print a[n] }

Produces:

0000000000000000011001100101010

abs

  • fix.abs →int

Returns the absolute value of fix.

-12345.abs # => 12345

12345.abs # => 12345

div

  • fix.div(numeric ) → integer

Division that always produces an integral result. Not affected by the mathn library (unlike Fixnum#/).

654321.div(13731) # => 47

654321.div(13731.34) # => 47

even?

  • fix.even? → true or false

Returns true if fix is even.

1.even? # => false

2.even? # => true

divmod

  • fix.divmod(numeric ) → array

See Numeric#divmod.

fdiv

  • fix.fdiv(numeric ) → float

Returns the floating-point result of dividing fix by numeric.

63.fdiv(9) # => 7.0

654321.fdiv(13731) # => 47.652829364212366

654321.fdiv(13731.24) # => 47.65199646936475

magnitude

  • fix.magnitude →int

Returns the magnitude of fix (the distance of fix from the origin of the number line). Synonym for Fixnum#abs. See also Complex#magnitude.

modulo

  • fix.modulo(numeric ) → numeric

Synonym for Fixnum#%.

654321.modulo(13731) # => 8964

654321.modulo(13731.24) # => 8952.72000000001

odd?

  • fix.odd? → true or false

Returns true if fix is odd.

1.odd? # => true

2.odd? # => false

size

  • fix.size →int

Returns the number of bytes in the machine representation of a Fixnum.

1.size # => 8

-1.size # => 8

2147483647.size # => 8

succ

  • fix.succ →int

Returns fix + 1.

1.succ # => 2

-1.succ # => 0

to_f

  • fix.to_f →float

Converts fix to a Float.

to_s

  • fix.to_s(base=10 ) → string

Returns a string containing the representation of fix radix base (2 to 36).

12345.to_s # => "12345"

12345.to_s(2) # => "11000000111001"

12345.to_s(8) # => "30071"

12345.to_s(10) # => "12345"

12345.to_s(16) # => "3039"

12345.to_s(36) # => "9ix"

84823723233035811745497171.to_s(36) # => "anotherrubyhacker"

zero?

  • fix.zero? → true or false

Returns true if fix is zero.

42.zero? # => false

0.zero? # => true

Class Float < Numeric

Float objects hold real numbers using the native architecture’s double-precision floating-point representation.

Constants

DIG

Precision of Float (in decimal digits).

EPSILON

The smallest Float such that 1.0+EPSILON != 1.0.

INFINITY

Positive infinity.

MANT_DIG

The number of mantissa digits (base RADIX).

MAX

The largest Float.

MAX_10_EXP

The maximum integer x such that 10x is a finite Float.

MAX_EXP

The maximum integer x such that FLT_RADIXx-1 is a finite Float.

MIN

The smallest Float.

MIN_10_EXP

The minimum integer x such that 10x is a finite Float.

MIN_EXP

The minimum integer x such that FLT_RADIXx-1 is a finite Float.

NAN

A value that is not a valid number.

RADIX

The radix of floating-point representations.

ROUNDS

The rounding mode for floating-point operations. Possible values include -1 if the mode is indeterminate, 0 if rounding is toward zero, 1 if rounding is to nearest representable value, 2 if rounding is toward infinity, and 3 if rounding is toward minus infinity.

Float: Instance methods

Arithmetic operations

Performs various arithmetic operations on flt.

flt

+

numeric

Addition

flt

--

numeric

Subtraction

flt

*

numeric

Multiplication

flt

/

numeric

Division

flt

%

numeric

Modulo

flt

**

numeric

Exponentiation

flt

-@

Unary minus

Comparisons

Compares flt to other numbers. < , <= , == , >= , > .

<=>

  • flt<=> numeric → -1, 0, +1, or nil

Returns -1, 0, or +1 depending on whether flt is less than, equal to, or greater than numeric.

==

  • flt== objtrue or false

Returns true only if obj has the same value as flt. Contrast this with Float#eql?, which requires obj to be a Float.

1.0 == 1.0 # => true

(1.0).eql?(1.0) # => true

1.0 == 1 # => true

(1.0).eql?(1) # => false

abs

  • flt.abs →numeric

Returns the absolute value of flt.

(-34.56).abs # => 34.56

-34.56.abs # => 34.56

ceil

  • flt.ceil →int

Returns the smallest integer greater than or equal to flt.

1.2.ceil # => 2

2.0.ceil # => 2

(-1.2).ceil # => -1

(-2.0).ceil # => -2

divmod

  • flt.divmod(numeric ) → array

See Numeric#divmod.

eql?

  • flt.eql?(obj ) → true or false

Returns true only if obj is a Float with the same value as flt. Contrast this with Float#==, which performs type conversions.

1.0.eql?(1) # => false

1.0 == 1 # => true

fdiv

  • flt.fdiv(number ) → float

Returns the floating-point result of dividing flt by number. Alias for Float#quo.

63.0.fdiv(9) # => 7.0

1234.56.fdiv(3.45) # => 357.8434782608695

finite?

  • flt.finite? → true or false

Returns true if flt is a valid IEEE floating-point number (it is not infinite, and nan? is false).

(42.0).finite? # => true

(1.0/0.0).finite? # => false

floor

  • flt.floor →int

Returns the largest integer less than or equal to flt.

1.2.floor # => 1

2.0.floor # => 2

(-1.2).floor # => -2

(-2.0).floor # => -2

infinite?

  • flt.infinite? → nil, -1, +1

Returns nil, -1, or +1 depending on whether flt is finite, -infinity, or +infinity.

(0.0).infinite? # => nil

(-1.0/0.0).infinite? # => -1

(+1.0/0.0).infinite? # => 1

magnitude

  • flt.magnitude →float

Returns the magnitude of flt (the distance of flt from the origin of the number line). Synonym for Float#abs. See also Complex#magnitude.

modulo

  • flt.modulo(numeric ) → numeric

Synonym for Float#%.

6543.21.modulo(137) # => 104.21000000000004

6543.21.modulo(137.24) # => 92.92999999999961

nan?

  • flt.nan? → true or false

Returns true if flt is an invalid IEEE floating-point number.

(-1.0).nan? # => false

(0.0/0.0).nan? # => true

quo

  • flt.quo(number ) → float

Returns the floating-point result of dividing flt by number.

63.0.quo(9) # => 7.0

1234.56.quo(3.45) # => 357.8434782608695

rationalize

  • flt.rationalize(<epsilon> ) → rational

Converts flt to a rational number with an approximate precision of epsilon. If epsilon is not given, a value will be chosen that preserves as many significant digits of the mantissa as possible.

1.3.rationalize # => (13/10)

1.333.rationalize # => (1333/1000)

1.33333333333333333.rationalize # => (4/3)

1.3333.rationalize(0.001) # => (4/3)

1.3333.rationalize(1) # => (1/1)

Math::PI.rationalize(0.01) # => (22/7)

round

  • flt.round(digits=0) →numeric

Rounds flt to the nearest integer if the parameter is omitted or zero or rounds to the given number of digits.

1.5.round # => 2

(-1.5).round # => -2

3.14159.round # => 3

3.14159.round(4) # => 3.1416

3.14159.round(2) # => 3.14

to_f

  • flt.to_f →flt

Returns flt.

to_i

  • flt.to_i →int

Returns flt truncated to an integer.

1.5.to_i # => 1

(-1.5).to_i # => -1

to_int

  • flt.to_int →int

Synonym for Float#to_i.

to_r

  • flt.to_r →number

Converts flt to a rational number.

1.5.to_r # => 3/2

(1.0/3).to_r # => 6004799503160661/18014398509481984

to_s

  • flt.to_s →string

Returns a string containing a representation of flt. As well as a fixed or exponential form of the number, the call may return NaN, Infinity, and -Infinity.

truncate

  • flt.truncate →int

Synonym for Float#to_i.

zero?

  • flt.zero? → true or false

Returns true if flt is 0.0.

Module GC

The GC module provides an interface to Ruby’s mark and sweep garbage collection mechanism. Some of the underlying methods are also available via the ObjectSpace module, described later.

GC: Module methods

count

  • GC.count →int

Returns a count of the number of times GC has run in the current process.

GC.count # => 4

res = ""

10_000.times { res += "wibble" }

GC.count # => 42

disable

  • GC.disable → true or false

Disables garbage collection, returning true if garbage collection was already disabled.

GC.disable # => false

GC.disable # => true

enable

  • GC.enable → true or false

Enables garbage collection, returning true if garbage collection was disabled.

GC.disable # => false

GC.enable # => true

GC.enable # => false

start

  • GC.start → nil

Initiates garbage collection, unless manually disabled.

GC.start # => nil

stat

  • GC.stat →stats_hash

Returns a hash containing GC statistics. The contents of this hash are implementation dependend. The method may not be present in all Ruby implementations.

GC.stat # => {:count=>4, :heap_used=>43, :heap_length=>43, :heap_increment=>0,

# .. :heap_live_num=>13938, :heap_free_num=>8659, :heap_final_num=>41,

# .. :total_allocated_object=>36625, :total_freed_object=>22687}

stress

  • GC.stress → true or false

Returns the current value of the stress flag (see GC.stress=).

stress=

  • GC.stress = true or falsetrue or false

Ruby will normally run garbage collection periodically. Setting the stress flag to true forces garbage collection to occur every time Ruby allocates a new object. This is typically used only for testing extensions (and Ruby itself).

GC.stress = true

GC: Instance methods

garbage_collect

  • garbage_collect → nil

Equivalent to GC.start.

include GC

garbage_collect # => nil

Module GC::Profiler

Provides low-level information on the state of garbage collection.

GC::Profiler.enable

animal = "cat"

22.times { animal *= 2 }

printf "Took %0.4fs in GC\n", GC::Profiler.total_time

GC::Profiler.report

GC::Profiler.disable

Produces:

Took 0.0040s in GC

GC 8 invokes.

Index Invoke Use Size Total Total GC Time(ms)

Time(sec) (byte) Size(byte) Object

1 0.034 334160 700040 17501 1.286000

2 0.039 329320 700040 17501 1.358000

3 0.045 329320 700040 17501 1.351000

4 0.056 329320 700040 17501 1.347000

GC::Profiler: Module methods

clear

  • GC::Profiler.clear → nil

Clears existing profile data.

disable

  • GC::Profiler.disable → nil

Disables the collection of profile data.

enable

  • GC::Profiler.enable → nil

Enables the collection of profile data.

enabled?

  • GC::Profiler.enabled? → true or false

Returns true if profile collection is enabled.

raw_data

  • GC::Profiler.raw_data → array of hashes

Return raw profiling data, in time order, as an array of hashes, where each hash contains a data sample.«2.0»

GC::Profiler.enable

animal = "cat"

22.times { animal *= 2 }

p GC::Profiler.raw_data.size

p GC::Profiler.raw_data[0, 2]

Produces:

5

[{:GC_TIME=>1.0999999999997123e-05, :GC_INVOKE_TIME=>0.03359,

:HEAP_USE_SIZE=>691000, :HEAP_TOTAL_SIZE=>700040, :HEAP_TOTAL_OBJECTS=>17501,

:GC_IS_MARKED=>false}, {:GC_TIME=>0.0014199999999999977,

:GC_INVOKE_TIME=>0.033891, :HEAP_USE_SIZE=>331080, :HEAP_TOTAL_SIZE=>700040,

:HEAP_TOTAL_OBJECTS=>17501, :GC_IS_MARKED=>0}]

report

  • GC::Profiler.report(to=STDOUT ) → nil

Writes the profile result to the given stream.

result

  • GC::Profiler.result → string

Returns a string containing a summary of the profile data.

total_time

  • GC::Profiler.total_time → float

Returns the total time spend in garbage collection during this profile run.

Class Hash < Object

Relies on:

each, <=>

A Hash is a collection of key/value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. The order in which keys and/or values are returned by the various iterators over hash contents will generally be the order that those entries were initially inserted into the hash.

Hashes have a default value. This value is returned when an attempt is made to access keys that do not exist in the hash. By default, this value is nil.

Mixes in

Enumerable

all?, any?, chunk, collect, collect_concat, count, cycle, detect, drop, drop_while, each_cons, each_entry, each_slice, each_with_index, each_with_object, entries, find, find_all, find_index, first, flat_map, grep, group_by, include?, inject, lazy, map, max, max_by, member?, min, min_by, minmax, minmax_by, none?, one?, partition, reduce, reject, reverse_each, select, slice_before, sort, sort_by, take, take_while, to_a, zip

Hash: Class methods

[ ]

  • Hash[<key => value>* ] → hsh
  • Hash[obj ] → hsh

Creates a new hash populated with the given objects. Equivalent to creating a hash using the literal { key => value, ...}. Keys and values occur in pairs, so there must be an even number of arguments. In the second form, obj must respond to to_hash .

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}

new

  • Hash.new →hsh
  • Hash.new(obj ) → hsh
  • Hash.new { |hash, key| … } →hsh

Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn’t correspond to a hash entry, the value returned depends on the style of new used to create the hash. In the first form, the access returns nil. If obj is specified, this single object will be used for all default values. If a block is specified, it will be called with the hash object and the key, and it should return the default value. It is the block’s responsibility to store the value in the hash if required.

h = Hash.new("Go Fish")

h["a"] = 100

h["b"] = 200

h["a"] # => 100

h["c"] # => "Go Fish"

# The following alters the single default object

h["c"].upcase! # => "GO FISH"

h["d"] # => "GO FISH"

h.keys # => ["a", "b"]

# While this creates a new default object each time

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"]

try_convert

  • Hash.try_convert(obj ) → a_hash or nil

If obj is not already a hash, attempts to convert it to one by calling its to_hash method. Returns nil if no conversion could be made.

class ConfigFile

def initialize(name)

@content = File.read(name)

end

def to_hash

result = {}

@content.scan(/^(\w+):\s*(.*)/) do |name, value|

result[name] = value

end

result

end

end

config = ConfigFile.new("some_config")

Hash.try_convert(config) # => {"user_name"=>"dave", "password"=>"wibble"}

Hash: Instance methods

==

  • hsh== objtrue or false

Equality—Two hashes are equal if they contain the same number of keys and the value corresponding to each key in the first hash is equal (using ==) to the value for the same key in the second. If obj is not a hash, attempts to convert it using to_hash and returns obj == hsh.

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

[ ]

  • hsh[key ] → value

Element Reference—Retrieves the value stored for key. If not found, returns the default value (see Hash.new for details).

h = { "a" => 100, "b" => 200 }

h["a"] # => 100

h["c"] # => nil

[ ]=

  • hsh[key ] = valuevalue

Element Assignment—Associates the value given by value with the key given by key. key should not have its value changed while it is in use as a key (a String passed as a key will be duplicated and frozen).

h = { "a" => 100, "b" => 200 }

h["a"] = 9

h["c"] = 4

h # => {"a"=>9, "b"=>200, "c"=>4}

assoc

  • hsh.assoc(key ) → [ key, val] or nil

Returns the two element array [ key, hsh[key] ] or nil if key does not reference an entry in the hash.

h = { "a" => 100, "b" => 200 } # => {"a"=>100, "b"=>200}

h.assoc("a") # => ["a", 100]

h.assoc("c") # => nil

clear

  • hsh.clear →hsh

Removes all key/value pairs from hsh.

h = { "a" => 100, "b" => 200 } # => {"a"=>100, "b"=>200}

h.clear # => {}

compare_by_identity

  • hsh.compare_by_identity →hsh

Hashes normally compare key values using eql? , which returns true if two objects have the same value. If you call compare_by_identity , keys will instead be considered to be equal only if they are the same object. Note that when strings are used as keys, they are automatically duplicated, so you will never be able to retrieve a string-keyed entry if keys are compared using identity.

key = "key"

h = { key => 100, 99 => "ninety nine" }

h[key] # => 100

h["key"] # => 100

h[99] # => "ninety nine"

h.compare_by_identity

h[key] # => nil

h["key"] # => nil

h[99] # => "ninety nine"

compare_by_identity?

  • hsh.compare_by_identity? → true or false

Returns true if hsh compares keys by identity.

default

  • hsh.default(key=nil ) → obj

Returns the default value, the value that would be returned by hsh[key] if key did not exist in hsh. See also Hash.new and Hash#default=.

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 # => nil

h.default(2) # => 20

default=

  • hsh.default =objhsh

Sets the value returned for a key that does not exist in the hash. Use Hash#default_proc= to set the proc to be called to calculate a default.

h = { "a" => 100, "b" => 200 }

h.default = "Go fish"

h["a"] # => 100

h["z"] # => "Go fish"

# This doesn't do what you might hope... (but see default_proc=)

h.default = lambda { |hash, key| hash[key] = key + key }

h[2] # => #<Proc:0x007fd91290e870@prog.rb:6 (lambda)>

h["cat"] # => #<Proc:0x007fd91290e870@prog.rb:6 (lambda)>

default_proc

  • hsh.default_proc →obj or nil

If Hash.new was invoked with a block, returns that block; otherwise, returns nil.

h = Hash.new {|h,k| h[k] = k*k } # => {}

p = h.default_proc # => #<Proc:0x007fbfe2847a20@prog.rb:1>

a = [] # => []

p.call(a, 2)

a # => [nil, nil, 4]

default_proc=

  • hsh.default_proc =procproc or nil

Sets the proc to be called to calculate values to be returned when a hash is accessed with a key it does not contain. Removes the default proc if passed nil.«2.0»

h = { "a" => 100, "b" => 200 }

h.default = "Go fish"

h["a"] # => 100

h["z"] # => "Go fish"

h.default_proc = lambda { |hash, key| hash[key] = key + key }

h[2] # => 4

h["cat"] # => "catcat"

delete

  • hsh.delete(key ) → value
  • hsh.delete(key ) { |key| … } → value

Deletes from hsh the entry whose key is to key, returning the corresponding value. If the key is not found, returns nil. If the optional code block is given and the key is not found, passes it the key and returns the result of block.

h = { "a" => 100, "b" => 200 }

h.delete("a") # => 100

h.delete("z") # => nil

h.delete("z") {|el| "#{el} not found" } # => "z not found"

delete_if

  • hsh.delete_if<key, value> → hsh or enumerator

Deletes every key/value pair from hsh for which block is true. Returns an Enumerator object if no block is given.

h = { "a" => 100, "b" => 200, "c" => 300 }

h.delete_if {|key, value| key >= "b" } # => {"a"=>100}

each

  • hsh.each { |key, value| … } →hsh

Calls block once for each key in hsh, passing the key and value as parameters.

h = { "a" => 100, "b" => 200 }

h.each {|key, value| puts "#{key} is #{value}" }

Produces:

a is 100

b is 200

each_key

  • hsh.each_key { |key| … } →hsh

Calls block once for each key in hsh, passing the key as a parameter.

h = { "a" => 100, "b" => 200 }

h.each_key {|key| puts key }

Produces:

a

b

each_pair

  • hsh.each_pair { |key, value| … } →hsh

Synonym for Hash#each.

each_value

  • hsh.each_value { |value| … } →hsh

Calls block once for each key in hsh, passing the value as a parameter.

h = { "a" => 100, "b" => 200 }

h.each_value {|value| puts value }

Produces:

100

200

empty?

  • hsh.empty? → true or false

Returns true if hsh contains no key/value pairs.

{}.empty? # => true

fetch

  • hsh.fetch(key <, default> ) → obj
  • hsh.fetch(key ) { |key| … } → obj}

Returns a value from the hash for the given key. If the key can’t be found, several options exist. With no other arguments, it will raise an IndexError exception; if default is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned. fetch does not evaluate any default values supplied when the hash was created—it looks only for keys in the hash.

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"

The following example shows that an exception is raised if the key is not found and a default value is not supplied.

h = { "a" => 100, "b" => 200 }

h.fetch("z")

Produces:

from prog.rb:2:in `<main>'

prog.rb:2:in `fetch': key not found: "z" (KeyError)

flatten

  • hsh.flatten(depth = 1 ) → an_array

Converts hsh to an array and then invokes Array#flatten! on the result.

h = { feline: [ "felix", "tom" ], equine: "ed" }

h.flatten # => [:feline, ["felix", "tom"], :equine, "ed"]

h.flatten(1) # => [:feline, ["felix", "tom"], :equine, "ed"]

h.flatten(2) # => [:feline, "felix", "tom", :equine, "ed"]

has_key?

  • hsh.has_key?(key ) → true or false

Returns true if the given key is present in hsh.

h = { "a" => 100, "b" => 200 }

h.has_key?("a") # => true

h.has_key?("z") # => false

has_value?

  • hsh.has_value?(value ) → true or false

Returns true if the given value is present for some key in hsh.

h = { "a" => 100, "b" => 200 }

h.has_value?(100) # => true

h.has_value?(999) # => false

include?

  • hsh.include?(key ) → true or false

Synonym for Hash#has_key?.

index

  • hsh.index(value ) → key

Deprecated—use Hash#key instead.

invert

  • hsh.invert →other_hash

Returns a new hash created by using hsh’s values as keys and using the keys as values. If hsh has duplicate values, the result will contain only one of them as a key—which one is not predictable.

h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }

h.invert # => {100=>"m", 300=>"y", 200=>"d", 0=>"a"}

keep_if

  • hsh.keep_if { |key, value| … } →hsh or enumerator

Modifies hsh by removing all elements for which block is false (see also Enumerable#select and Hash.select!.) Returns an Enumerator object if no block is given.

a = { a: 1, b: 2, c: 3}

a.keep_if {|key, value| key =~ /[bc]/ } # => {:b=>2, :c=>3}

a # => {:b=>2, :c=>3}

a.keep_if {|key, value| value.odd? } # => {:c=>3}

a # => {:c=>3}

key

  • hsh.key(value ) → key or nil

Returns the key of the first hash entry whose value is value.

h = { a: 100, b: 200, c: 100 }

h.key(100) # => :a

h.key(200) # => :b

h.key(300) # => nil

key?

  • hsh.key?(key ) → true or false

Synonym for Hash#has_key?.

keys

  • hsh.keys →array

Returns a new array populated with the keys from this hash. See also Hash#values.

h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }

h.keys # => ["a", "b", "c", "d"]

length

  • hsh.length →fixnum

Returns the number of key/value pairs in the hash.

h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }

h.length # => 4

h.delete("a") # => 200

h.length # => 3

member?

  • hsh.member?(key ) → true or false

Synonym for Hash#has_key?.

merge

  • hsh.merge(other_hash ) → result_hash
  • hsh.merge(other_hash ) { |key, old_val, new_val| … } → result_hash

Returns a new hash containing the contents of other_hash and the contents of hsh. With no block parameter, overwrites entries in hsh with duplicate keys with those from other_hash. If a block is specified, it is called with each duplicate key and the values from the two hashes. The value returned by the block is stored in the new hash.

h1 = { "a" => 100, "b" => 200 }

h2 = { "b" => 254, "c" => 300 }

h1.merge(h2) # => {"a"=>100, "b"=>254, "c"=>300}

h1.merge(h2) {|k,o,n| o} # => {"a"=>100, "b"=>200, "c"=>300}

h1 # => {"a"=>100, "b"=>200}

merge!

  • hsh.merge!(other_hash ) → hsh
  • hsh.merge!(other_hash ) { |key, old_val, new_val| … } → hsh

Like Hash#merge but changes the contents of hsh.

h1 = { "a" => 100, "b" => 200 }

h2 = { "b" => 254, "c" => 300 }

h1.merge!(h2) # => {"a"=>100, "b"=>254, "c"=>300}

h1 # => {"a"=>100, "b"=>254, "c"=>300}

rassoc

  • hsh.rassoc(val ) → [ key, val] or nil

Searches hsh for the first element whose value is val, returning the key and value as a two-element array. Returns nil if the value does not occur in the hash.

h = { "a" => 100, "b" => 200, "c" => 100 }

h.rassoc(100) # => ["a", 100]

h.rassoc(200) # => ["b", 200]

rehash

  • hsh.rehash →hsh

Rebuilds the hash based on the current hash values for each key. If values of key objects have changed since they were inserted, this method will reindex hsh. If Hash#rehash is called while an iterator is traversing the hash, an IndexError will be raised in the iterator.

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

reject

  • hsh.reject { |key, value| … } →hash

Same as Hash#delete_if but uses (and returns) a copy of hsh. Equivalent to hsh.dup.delete_if.

reject!

  • hsh.reject!<key, value> → hsh or enumerator

Equivalent to Hash#delete_if but returns nil if no changes were made. Returns an Enumerator object if no block is given.

replace

  • hsh.replace(other_hash ) → hsh

Replaces the contents of hsh with the contents of other_hash.

h = { "a" => 100, "b" => 200 }

h.replace({ "c" => 300, "d" => 400 }) # => {"c"=>300, "d"=>400}

select

  • hsh.select { |key, value| … } →hash

Returns a new hash consisting of [ key, value] pairs for which the block returns true. Also see Hash#values_at. (This behavior differs from Ruby 1.8, which returns an array of arrays.)

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}

select!

  • hsh.select! { |key, value| … } →hsh, nil, or enumerator

Modifies hsh by removing all elements for which block is false (see also Enumerable#select and Hash#keep_if). Returns nil if no changes were made or returns an Enumerator object if no block is given. Otherwise, returns hsh.

a = { a: 1, b:2, c: 3}

a.select! {|key, value| value < 2 } # => {:a=>1}

a # => {:a=>1}

a.select! {|key, value| value < 3 } # => nil

a # => {:a=>1}

shift

  • hsh.shift →array or nil

Removes a key/value pair from hsh and returns it as the two-item array [ key, value ]. If the hash is empty, returns the default value, calls the default proc (with a key value of nil), or returns nil.

h = { 1 => "a", 2 => "b", 3 => "c" }

h.shift # => [1, "a"]

h # => {2=>"b", 3=>"c"}

size

  • hsh.size →fixnum

Synonym for Hash#length.

sort

  • hsh.sort →array
  • hsh.sort { |a, b| … } →array

Converts hsh to a nested array of [ key, value ] arrays and sorts it, using Array#sort. (Technically this is just the sort method of Enumerable. It’s documented here because it’s unusual for sort to return a different type.)

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]]

store

  • hsh.store(key, value ) → value

Synonym for Element Assignment (Hash#[]=).

to_a

  • hsh.to_a →array

Converts hsh to a nested array of [ key, value ] arrays.

h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }

h.to_a # => [["c", 300], ["a", 100], ["d", 400]]

to_h

  • hsh.to_h →hsh

Returns the hash. Converts the receiver to a hash if send to a subclass of Hash.«2.0»

to_hash

  • hsh.to_hash →hsh

See the discussion in the ducktyping chapter.

to_s

  • hsh.to_s →string

Converts hsh to a string by converting the hash to an array of [ key, value ] pairs and then converting that array to a string using Array#join with the default separator.

h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }

h.to_s # => "{\"c\"=>300, \"a\"=>100, \"d\"=>400}"

update

  • hsh.update(other_hash ) → hsh
  • hsh.update(other_hash ) { |key, old_val,new_val| … } → hsh

Synonym for Hash#merge!.

value?

  • hsh.value?(value ) → true or false

Synonym for Hash#has_value?.

values

  • hsh.values →array

Returns an array populated with the values from hsh. See also Hash#keys.

h = { "a" => 100, "b" => 200, "c" => 300 }

h.values # => [100, 200, 300]

values_at

  • hsh.values_at(<key>+ ) → array

Returns an array consisting of values for the given key(s). Will insert the default value for keys that are not found.

h = { "a" => 100, "b" => 200, "c" => 300 }

h.values_at("a", "c") # => [100, 300]

h.values_at("a", "c", "z") # => [100, 300, nil]

h.default = "cat"

h.values_at("a", "c", "z") # => [100, 300, "cat"]

Class Integer < Numeric

Subclasses are:

Bignum, Fixnum

Integer is the basis for the two concrete classes that hold whole numbers, Bignum and Fixnum.

Integer: Instance methods

ceil

  • int.ceil →integer

Synonym for Integer#to_i.

chr

  • int.chr →string
  • int.chr(encoding) →string

Returns a string containing the character represented by the receiver’s value. Values less that 128 are always returned as ASCII. The encoding of strings representing higher values can be set using the optional parameter.

65.chr # => "A"

?a.chr # => "a"

233.chr # => "\xE9"

233.chr(Encoding::UTF_8) # => "é"

denominator

  • int.denominator →integer

Converts the denominator of the rational representation of int.

1.denominator # => 1

1.5.denominator # => 2

num = 1.0/3

num.to_r # => (6004799503160661/18014398509481984)

num.denominator # => 18014398509481984

downto

  • int.downto(integer ) { |i| … } → int

Iterates block, passing decreasing values from int down to and including integer.

5.downto(1) {|n| print n, ".. " }

print " Liftoff!\n"

Produces:

5.. 4.. 3.. 2.. 1.. Liftoff!

even?

  • int.even? → true or false

Returns true if int is even.

1.even? # => false

2.even? # => true

floor

  • int.floor →integer

Returns the largest integer less than or equal to int. Equivalent to Integer#to_i.

1.floor # => 1

(-1).floor # => -1

gcd

  • int.gcd(other_integer ) → integer

Returns the greatest common denominator of int and other_integer.

10.gcd(15) # => 5

10.gcd(16) # => 2

10.gcd(17) # => 1

gcdlcm

  • int.gcdlcm(other_integer ) → [ gcd, lcm ]

Returns both the GCD and the LCM of int and other_integer.

10.gcdlcm(15) # => [5, 30]

10.gcdlcm(16) # => [2, 80]

10.gcdlcm(17) # => [1, 170]

integer?

  • int.integer? → true

Always returns true.

lcm

  • int.lcm(other_integer ) → integer

Returns the lowest common multiple of int and other_integer.

10.lcm(15) # => 30

10.lcm(20) # => 20

10.lcm(-2) # => 10

next

  • int.next →integer

Returns the Integer equal to int+1.

1.next # => 2

(-1).next # => 0

numerator

  • int.numerator →integer

Converts the numerator of the rational representation of int.

1.numerator # => 1

1.5.numerator # => 3

num = 1.0/3

num.to_r # => (6004799503160661/18014398509481984)

num.numerator # => 6004799503160661

odd?

  • int.odd? → true or false

Returns true if int is odd.

1.odd? # => true

2.odd? # => false

ord

  • int.ord →int

The ord method was added to assist in the migration from Ruby 1.8 to 1.9. It allows ?A.ord to return 65. If ?A returns a string, ord will be called on that string and return 65; if ?A returns an integer, then Numeric#ord is called, which is basically a no-op.

pred

  • int.pred →integer

Returns int - 1.

rationalize

  • int.rationalize(eps=nil ) → rational

Returns the rational number int/1. The argument is always ignored. Effectively a synonym for Integer.to_r.

99.rationalize # => (99/1)

-12345678.rationalize(99) # => (-12345678/1)

round

  • int.round →integer

Synonym for Integer#to_i.

succ

  • int.succ →integer

Synonym for Integer#next.

times

  • int.times { |i| … } →int

Iterates block int times, passing in values from zero to int - 1.

5.times do |i|

print i, " "

end

Produces:

0 1 2 3 4

to_i

  • int.to_i →int

Returns int.

to_int

  • int.to_int →integer

Synonym for Integer#to_i.

to_r

  • int.to_r →number

Converts int to a rational number.

1.to_r # => 1/1

-1.to_r # => -1/1

truncate

  • int.truncate →integer

Synonym for Integer#to_i.

upto

  • int.upto(integer ) { |i| … } → int

Iterates block, passing in integer values from int up to and including integer.

5.upto(10) {|i| print i, " " }

Produces:

5 6 7 8 9 10

Class IO < Object

Subclasses are:

File

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 | 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.

The IO class uses the Unix abstraction of file descriptors (fds), small integers that represent open files. Conventionally, standard input has an fd of 0, standard output has an fd of 1, and standard error has an fd of 2.

Ruby will convert path names between different operating system conventions if possible. For instance, on Windows the filename /gumby/ruby/test.rb will be opened as \gumby\ruby\test.rb. When specifying a Windows-style filename in a double-quoted 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 . This mode string must be one of the values listed in Table 16, Mode values. As of Ruby 1.9, the mode may also contain information on the external and internal encoding of the data associated with the port. If an external encoding is specified, Ruby assumes that the data it received from the operating system uses that encoding. If no internal encoding is given, strings read from the port will have this encoding. If an internal encoding is given, data will be transcoded from the external to the internal encoding, and strings will have that encoding. The reverse happens on output.

Mixes in

Enumerable

all?, any?, chunk, collect, collect_concat, count, cycle, detect, drop, drop_while, each_cons, each_entry, each_slice, each_with_index, each_with_object, entries, find, find_all, find_index, first, flat_map, grep, group_by, include?, inject, lazy, map, max, max_by, member?, min, min_by, minmax, minmax_by, none?, one?, partition, reduce, reject, reverse_each, select, slice_before, sort, sort_by, take, take_while, to_a, zip

IO: Class methods

binread

  • IO.binread(name <, length offset> ) → string

Opens name with mode rb:ASCII-8BIT, reads length bytes starting at offset, and then closes the file. The bytes are returned in a string with ASCII-8BIT encoding. offset defaults to 0, and length defaults to the number of bytes between offset and the end of the file.

IO.binread("testfile", 20) # => "This is line one\nThi"

IO.binread("testfile", 20, 20) # => "s is line two\nThis i"

str = IO.binread("testfile")

str.encoding # => #<Encoding:ASCII-8BIT>

str1 = IO.read("testfile")

str1.encoding # => #<Encoding:UTF-8>

binwrite

  • IO.binwrite(portname, string <, offset> <, options>) → int

Opens the file for writing with mode wb:ASCII-8BIT, optionally seeks to the given offset, and then writes string. Returns the number of bytes written. The file is truncated before writing if no offset is specified.

options is an optional hash used to pass parameters to the underlying open call used by write . See IO.foreach for details.

copy_stream

  • IO.copy_stream(from, to <, max_length offset> ) → integer

Copies from to to. These may be specified either as filenames or as open I/O streams. You may optionally specify a maximum length to copy and a byte offset to start the copy from. Returns the number of bytes copied.

IO.copy_stream("testfile", "newfile", 10, 10)

ip = File.open("/etc/passwd")

op = File.open("extract", "w")

op.puts "First 20 characters of /etc/passwd"

IO.copy_stream(ip, op, 20)

op.puts "\nEnd of extract"

op.close

puts File.readlines("extract")

Produces:

First 20 characters of /etc/passwd

##

# User Database

#

End of extract

for_fd

  • IO.for_fd(int, mode ) → io

Synonym for IO.new.

foreach

  • IO.foreach(portname, separator=$/ <, options> ) { |line| … } → nil
  • IO.foreach(portname, limit <, options> ) { |line| … } → nil
  • IO.foreach(portname, separator, limit <, options> ) { |line| … } → nil

Executes the block for every line in the named I/O port, where lines are separated by separator. If separator is nil, the entire file is passed as a single string. If the limit argument is present and positive, at most that many characters will be returned in each iteration. If only the limit argument is given and that argument is negative, then encodings will be ignored while looking for the record separator, which increases performance.

IO.foreach("testfile") {|x| puts "GOT: #{x}" }

Produces:

GOT: This is line one

GOT: This is line two

GOT: This is line three

GOT: And so on...

options is an optional hash used to pass parameters to the underlying open call used by read . It may contain one or more of the following:

encoding:

The encoding for the string, either as "external" or "external:internal"

mode:

The mode string to be passed to open

open_args:

An array containing the arguments to be passed to open; other options are ignored if this one is present

IO.foreach("testfile", nil, mode: "rb", encoding: "ascii-8bit") do |content|

puts content.encoding

end

IO.foreach("testfile", nil, open_args: ["r:iso-8859-1"]) do |content|

puts content.encoding

end

Produces:

ASCII-8BIT

ISO-8859-1

new

  • IO.new(integer_fd, mode="r" <, options> ) → io

Returns a new IO object (a stream) for the given integer file descriptor and mode. The mode and options may be given as for File.new (see Table 16, Mode values, and see Table 17, File and I/O open options). 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

# encoding: utf-8

b = IO.new(2, mode: "w", encoding: "utf-8", crlf_newline: true)

b.puts "olé"

Produces:

olé

open

  • IO.open(<args>+ ) → io
  • IO.open(<args>+ ) { |io| … } → obj

IO.open creates a new IO object, passing args to that object’s initialize method. If no block is given, simply returns that object. If a block is given, passes the IO object to the block. When the block exits (even via exception or program termination), the io object will be closed. If the block is present, IO.open returns the value of the block. The rough implementation is as follows:

class IO

def open(*args)

file = return_value = self.new(*args)

begin

return_value = yield(file)

ensure

file.close

endif block_given?

return_value

end

end

Note that subclasses of IO such as File can use open even though their constructors take different parameters. Calling File.open(...) will invoke File’s constructor, not IO’s.

IO.open(1, "w") do |io|

io.puts "Writing to stdout"

end

Produces:

Writing to stdout

File.open("testfile", mode: "r", encoding: "utf-8") do |f|

puts f.read

end

Produces:

This is line one

This is line two

This is line three

And so on...

pipe

  • IO.pipe → [read_io, write_io ]
  • IO.pipe(encoding_string <, encoding_options> ) → [ read_io, write_io ]
  • IO.pipe(external, internal <, encoding_options> ) → [ read_io, write_io ]
  • IO.pipe( ... as above ... ) { |read_io, write_io| … }

Creates a pair of pipe endpoints (connected to each other) and returns them as a two-element array of IO objects. write_io is automatically placed into sync mode. Not available on all platforms.

Encodings for the pipes can be specified as a string ("external" or "external:internal") or as two arguments specifying the external and internal encoding names (or encoding objects). If both external and internal encodings are present, the encoding_options parameter specifies conversion options (see Table 22, Options to encode and encode!).

If a block is given, it is passed the two I/O objects. They will be closed at the end of the block if they are still open.

In the following example, 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 any writers have 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.

IO.pipe do |rd, wr|

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

end

Produces:

Sending message to parent

Parent got: <Hi Dad>

popen

  • IO.popen(cmd, mode="r" ) → io
  • IO.popen(cmd, mode="r" ) { |io| … } → obj

Runs the specified command string as a subprocess; the subprocess’s standard input and output will be connected to the returned IO object. The parameter cmd may be a string or (in Ruby 1.9) an array of strings. In the latter case, the array is used as the argv parameter for the new process, and no special shell processing is performed on the strings. In addition, if the array starts with a hash, it will be used to set environment variables in the subprocess, and if it ends with a hash, the hash will be used to set execution options for the subprocess. See Object#spawn for details. If cmdis a string, it will be subject to shell expansion. If the cmd string starts with a minus sign (-) and the operating system supports fork(2), then the current Ruby process is forked. The default mode for the new file object is r, but mode may be set to any of the modes in Table 16, Mode values.

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. 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. Also see the Open3 library and Object#exec.

pipe = IO.popen("uname")

p(pipe.readlines)

puts "Parent is #{Process.pid}"

IO.popen("date") {|pipe| puts pipe.gets }

IO.popen("-") {|pipe| STDERR.puts "#{Process.pid} is here, pipe=#{pipe}" }

Process.waitall

Produces:

["Darwin\n"]

Parent is 23465

Mon May 27 12:32:20 CDT 2013

23465 is here, pipe=#<IO:0x007f935290e768>

23468 is here, pipe=

Here’s an example that uses the Ruby 1.9 options to merge standard error and standard output into a single stream. Note that buffering means that the error output comes back ahead of the standard output.

pipe = IO.popen([ "bc", { STDERR => STDOUT }], "r+" )

pipe.puts '1 + 3; bad_function()'

pipe.close_write

puts pipe.readlines

Produces:

Runtime error (func=(main), adr=8): Function bad_function not defined.

4

read

  • IO.read(portname, <length=$/ offset> <, options> ) → string

Opens the file, optionally seeks to the given offset, and then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

options is an optional hash used to pass parameters to the underlying open call used by read . See IO.foreach for details.

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 "

readlines

  • IO.readlines(portname, separator=$/ <, options> ) → array
  • IO.readlines(portname, limit <, options> ) → array
  • IO.readlines(portname, separator, limit <, options> ) → array

Reads the entire file specified by portname as individual lines and returns those lines in an array. Lines are separated by separator. If separator is nil, the entire file is passed as a single string. If the limit argument is present and positive, at most that many characters will be returned in each iteration. If only the limit argument is given and that argument is negative, then encodings will be ignored while looking for the record separator, which increases performance. options is an optional hash used to pass parameters to the underlying open call used by read . See IO.foreach for details.

a = IO.readlines("testfile")

a[0] # => "This is line one\n"

select

  • IO.select(read_array <, write_array error_array timeout> ) → array or nil

See Object#select.

sysopen

  • IO.sysopen(path, <mode perm> ) → int

Opens the given path, returning the underlying file descriptor as a Fixnum.

IO.sysopen("testfile") # => 5

try_convert

  • IO.try_convert(obj ) → an_io or nil

If obj is not already an I/O object, attempts to convert it to one by calling its to_io method. Returns nil if no conversion could be made.

class SillyIOObject

def to_io

STDOUT

end

end

IO.try_convert(SillyIOObject.new) # => #<IO:<STDOUT>>

IO.try_convert("Shemp") # => nil

write

  • IO.write(portname, string <, offset> <, options>) → int

Opens the file for writing, optionally seeks to the given offset, and then writes string. Returns the number of bytes written. The file is truncated before writing if no offset is specified.

options is an optional hash used to pass parameters to the underlying open call used by read . See IO.foreach for details.

IO.write("somefile", "my string") # => 9

IO.read("somefile") # => "my string"

IO.write("somefile", "adden", 1) # => 5

IO.read("somefile") # => "maddening"

IO: Instance methods

<<

  • io<< objio

String Output—Writes obj to io. obj will be converted to a string using to_s .

STDOUT << "Hello " << "world!\n"

Produces:

Hello world!

advise

  • io.advise(advice,offset=0, length=0) → nil

Help your operating system optimize I/O by telling it how you plan to access this I/O object. The first parameter is a symbol from this table:

Table 19. advice parameter to advise

:normal

No particular access pattern is being given.

:sequential

The portion will be read sequentially.

:random

The portion will be read in random order.

:willneed

The portion will be needed in the near future.

:dontneed

The portion will not be needed in the near future.

:noreuse

The portion will not be reused in the near future.

The second and third parameters denote the region of the file to be accessed. Their default values of zeroes mean the entire file. See the posix_fadvise(2) man page for details.

autoclose=

  • io.autoclose = true or false →io

Normally when an I/O object is finalized, the corresponding fd is automatically closed. By setting autoclose=false, you prevent this behavior. This is useful if you’re using an I/O object to access an fd that’s open elsewhere in your program, and you don’t want to affect that other object.

autoclose?

  • io.autoclose? → true or false

Returns the state of the autoclose flag for io.

binmode

  • io.binmode →io

Puts io into binary mode. It is more common to use the "b" modifier in the mode string to set binary mode when you open a file. Binary mode is required when reading or writing files containing bit sequences that are not valid in the encoding of the file. Once a stream is in binary mode, it cannot be reset to nonbinary mode.

binmode?

  • io.binmode? → true or false

Returns true if io is in binary mode.

f = File.open("/etc/passwd")

f.binmode? # => false

f = File.open("/etc/passwd", "rb:binary")

f.binmode? # => true

bytes

  • io.bytes →enumerator

Returns an enumerator that iterates over the bytes (not characters) in io, returning each as an integer. See also IO#getbyte. Deprecated in Ruby 2.0.«2.0»

enum = File.open("testfile").bytes # => prog.rb:1: warning: IO#bytes is

# .. deprecated; use #each_byte instead

enum.first(10) # => [84, 104, 105, 115, 32, 105, 115, 32,

# .. 108, 105]

chars

  • io.chars →enumerator

Returns an enumerator that allows iteration over the characters in io. Deprecated in Ruby 2.0.«2.0»

enum = File.open("testfile").chars # => prog.rb:1: warning: IO#chars is

# .. deprecated; use #each_char instead

enum.first(7) # => ["T", "h", "i", "s", " ", "i", "s"]

close

  • io.close → nil

Closes io 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.

close_on_exec?

  • io.close_on_exec? → true or false

Returns the state of the close on exec flag for io. Raises NotImplemented if not available.

close_on_exec=

  • io.close_on_exec = true or false → nil

Sets the close on exec flag for io. Raises NotImplemented if not available. I/O objects with this flag set will be closed across exec() calls.

close_read

  • io.close_read → nil

Closes the read end of a duplex I/O stream (in other words, one that contains both a read and a write stream, such as a pipe). Raises IOError if the stream is not duplexed.

f = IO.popen("/bin/sh","r+")

f.close_read

f.readlines

Produces:

from prog.rb:3:in `<main>'

prog.rb:3:in `readlines': not opened for reading (IOError)

close_write

  • io.close_write → nil

Closes the write end of a duplex I/O stream (in other words, one that contains both a read and a write stream, such as a pipe). Will raise IOError if the stream is not duplexed.

closed?

  • io.closed? → true or false

Returns true if io is completely closed (for duplex streams, both reader and writer) and returns 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

codepoints

  • io.codepoints { |codepoint| … } →io
  • io.codepoints →enumerator

Synonym for IO#each_codepoint. Deprecated in Ruby 2.0.«2.0»

each

  • io.each(separator=$/ ) { |line| … } → io
  • io.each(limit ) { |line| … } → io
  • io.each(separator, limit ) { |line| … } → io
  • io.each(args.. ) → enum

Executes the block for every line in io, where lines are separated by separator. If separator is nil, the entire file is passed as a single string. If the limit argument is present and positive, at most that many characters will be returned in each iteration. If only the limit argument is given and that argument is negative, then encodings will be ignored while looking for the record separator, which increases performance. Returns an enumerator if no block is given.

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...

each_byte

  • io.each_byte { |byte| … } → nil
  • io.each_byte →enum

Calls the given block once for each byte (a Fixnum in the range 0 to 255) in io, passing the byte as an argument. The stream must be opened for reading, or IOerror will be raised. Returns an enumerator if no block is given.

f = File.new("testfile")

checksum = 0

f.each_byte {|x| checksum ^= x } # => #<File:testfile>

checksum # => 12

each_char

  • io.each_char { |char| … } → nil
  • io.each_char →enum

Calls the given block, passing it each character (a string of length 1) in io. The stream must be opened for reading, or an IOerror will be raised. Returns an enumerator if no block is given.

f = File.new("testfile")

result = []

f.each_char {|ch| result << ch} # => #<File:testfile>

result[0, 5] # => ["T", "h", "i", "s", " "]

each_codepoint

  • io.each_codepoint { |codepoint| … } →io
  • io.each_codepoint →enumerator

Iterates over the codepoints in io, returning each as an integer. With no block, an enumerator is returned.

#encoding: utf-8

File.open("/tmp/testfile", "w:utf-8") { |f| f.puts "∂og" }

File.open("/tmp/testfile") do |f|

f.each_codepoint { |codepoint| printf "%#X ", codepoint }

end

Produces:

0X2202 0X6F 0X67 0XA

each_line

  • io.each_line(...) { |line| … } →io

Synonym for IO#each.

eof

  • io.eof → true or false

Returns true if io is at the end of the file. The stream must be opened for reading, or an IOError will be raised.

f = File.open("testfile")

f.eof # => false

dummy = f.readlines

f.eof # => true

eof?

  • io.eof? → true or false

Synonym for IO#eof.

external_encoding

  • io.external_encoding →encoding

Returns the encoding object representing the external encoding of this I/O object.

io = File.open("testfile", "r:utf-8:iso-8859-1")

io.external_encoding # => #<Encoding:UTF-8>

io.internal_encoding # => #<Encoding:ISO-8859-1>

fcntl

  • io.fcntl(cmd, arg ) → int

Provides a mechanism for issuing low-level commands to control or query file-oriented I/O streams. Commands (which are integers), arguments, and the result 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 fcntl(2) for details. See the Fcntl module for symbolic names for the first argument. Not implemented on all platforms.

fdatasync

  • io.fdatasync → 0

Uses the operating system’s fdatasync(2) call to write all buffered data associated with io. Raises an exception if the operating system does not support fdatasync(2).

fileno

  • io.fileno →int

Returns an integer representing the numeric file descriptor for io.

STDIN.fileno # => 0

STDOUT.fileno # => 1

flush

  • io.flush →io

Flushes any buffered data within io 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

fsync

  • io.fsync → 0 or nil

Immediately writes all buffered data in io 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 does not guarantee that the underlying operating system actually writes it to disk.

getbyte

  • io.getbyte →fixnum or nil

Returns the next 8-bit byte (as opposed to an encoded character) from io or returns nil at the end of the file. See also IO#bytes.

file = File.open("testfile")

file.getbyte # => 84

file.getbyte # => 104

getc

  • io.getc →string or nil

Gets the next character from io. Returns nil if called at the end of the file.

f = File.new("testfile")

f.getc # => "T"

f.getc # => "h"

gets

  • io.gets(separator=$/ ) → string or nil
  • io.gets(limit ) → string or nil
  • io.gets(separator, limit ) → string or nil

Reads the next “line” from the I/O stream; lines are separated by separator. A separator of nil reads the entire contents, and a zero-length separator reads the input a paragraph at a time (two or more successive newlines in the input separate paragraphs). If the limit argument is present and positive, at most that many characters will be returned in each iteration. If only the limit argument is given and that argument is negative, then encodings will be ignored while looking for the record separator, which increases performance. The line read in will be returned and also assigned to $_ (although the setting of $_ is considered ugly—it may be removed in future). Returns nil if called at the end of the file.

file = File.new("testfile")

file.gets # => "This is line one\n"

$_ # => "This is line one\n"

file.gets(10) # => "This is li"

file.gets("line") # => "ne two\nThis is line"

file.gets("line", 4) # => " thr"

internal_encoding

  • io.internal_encoding →encoding

Returns the encoding object representing the internal encoding of this I/O object.

io = File.open("testfile", "r:utf-8:iso-8859-1")

io.external_encoding # => #<Encoding:UTF-8>

io.internal_encoding # => #<Encoding:ISO-8859-1>

ioctl

  • io.ioctl(cmd, arg ) → int

Provides a mechanism for issuing low-level commands to control or query I/O devices. The command (which is an integer), 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.

isatty

  • io.isatty → true or false

Returns true if io is associated with a terminal device (tty) and returns false otherwise.

File.new("testfile").isatty # => false

File.new("/dev/tty").isatty # => true

lineno

  • io.lineno →int

Returns the current line number in io, which 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

lineno=

  • io.lineno =intint

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

$. # => 1

f.gets # => "This is line two\n"

$. # => 1001

lines

  • io.lines(separator=$/ ) → enumerator
  • io.lines(limit ) → enumerator
  • io.lines(separator, limit ) → enumerator

Returns an enumerator that allows iteration over the lines in io, where lines are terminated by separator. If separator is nil, the entire file is passed as a single string. If the limit argument is present and positive, at most that many characters will be returned in each iteration. If only the limitargument is given and that argument is negative, then encodings will be ignored while looking for the record separator, which increases performance. Deprecated in Ruby 2.0.«2.0»

pid

  • io.pid →int

Returns the process ID of a child process associated with io. This will be set by IO.popen.

pipe = IO.popen("-")

if pipe

STDERR.puts "In parent, child pid is #{pipe.pid}"

pipe.close

else

STDERR.puts "In child, pid is #{$$}"

end

Produces:

In parent, child pid is 23528

In child, pid is 23528

pos

  • io.pos →int

Returns the current offset (in bytes) of io.

f = File.new("testfile")

f.pos # => 0

f.gets # => "This is line one\n"

f.pos # => 17

pos=

  • io.pos =int → 0

Seeks to the given position (in bytes) in io.

f = File.new("testfile")

f.pos = 17

f.gets # => "This is line two\n"

print

  • io.print(<obj=$_>* ) → nil

Writes the given object(s) to io. 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. Returns nil.

STDOUT.print("This is ", 100, " percent.\n")

Produces:

This is 100 percent.

printf

  • io.printf(format <, obj>* ) → nil

Formats and writes to io, converting parameters under control of the format string. See the description Object#sprintf for details.

putc

  • io.putc(obj ) → obj

If obj is a string, write its first character. Otherwise treat obj as a number, and write its low-order byte as a character. Note that this is not encoding safe, because the byte may be just part of a multibyte sequence.

#encoding: utf-8

STDOUT.putc "ABC"

STDOUT.putc "∂og"

STDOUT.putc 65

Produces:

A∂A

puts

  • io.puts(<obj>* ) → nil

Writes the given objects to io as with IO#print. Writes 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 newline.

STDOUT.puts("this", "is", "a", "test")

Produces:

this

is

a

test

read

  • io.read(<int buffer> ) → string or nil

Reads at most int bytes from the I/O stream or to the end of the file if int is omitted. Returns nil if called at the end of the file. If buffer (a string) is provided, it is resized accordingly, and input is read directly into it.

f = File.new("testfile")

f.read(16) # => "This is line one"

str = "cat"

f.read(10, str) # => "\nThis is l"

str # => "\nThis is l"

readbyte

  • io.readbyte →fixnum

Returns the next 8-bit byte (as opposed to an encoded character) from io, raising EOFError at end of file. See also IO#bytes.

readchar

  • io.readchar →string

Reads a character as with IO#getc but raises an EOFError on end of file.

readline

  • io.readline(separator=$/ ) → string or nil
  • io.readline(limit ) → string or nil
  • io.readline(separator, limit ) → string or nil

Reads a line as with IO#gets but raises an EOFError on end of file.

readlines

  • io.readlines(separator=$/ ) → array
  • io.readlines(limit ) → array
  • io.readlines(separator, limit ) → array

Returns all of the lines in io as an array. Lines are separated by the optional separator. If separator is nil, the entire file is passed as a single string. If the limit argument is present and positive, at most that many characters will be returned in each iteration. If only the limit argument is given and that argument is negative, then encodings will be ignored while looking for the record separator, which increases performance.

f = File.new("testfile")

f.readlines # => ["This is line one\n", "This is line two\n", "This is

# .. line three\n", "And so on...\n"]

f = File.new("testfile")

f.readlines("line") # => ["This is line", " one\nThis is line", " two\nThis is

# .. line", " three\nAnd so on...\n"]

f = File.new("testfile")

f.readlines(10) # => ["This is li", "ne one\n", "This is li", "ne two\n",

# .. "This is li", "ne three\n", "And so on.", "..\n"]

readpartial

  • io.readpartial(limit, result="" ) → result

Data read from files and devices is normally buffered. When reading line by line (for example using IO#gets), Ruby will read many lines at a time into an internal buffer and then return lines from that buffer. This buffering is normally transparent—Ruby will refill the buffer automatically when required. However, when reading from a device or pipe (as opposed to a file), you sometimes want to read whatever is in the buffer, reading from the device or pipe only if the buffer is empty when the read starts. This is what readpartial does—it returns any data available in local buffers immediately, only reading from the device or pipe (potentially blocking) if the buffer is empty. Raises EOFError when it reached EOF. See also IO#read_nonblock.

The following example comes from the internal documentation, with thanks to the anonymous author:

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" "" ""

read_nonblock

  • io.readpartial(limit, result="" ) → result

Effectively the same as IO#readpartial, except in cases where no buffered data is available. In this case, it puts io into nonblocking mode before attempting to read data. This means that the call may return EAGAIN and EINTR errors, which should be handled by the caller.

reopen

  • io.reopen(other_io ) → io
  • io.reopen(path, mode ) → io

Reassociates io 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"

rewind

  • io.rewind → 0

Positions io 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"

seek

  • io.seek(int, whence=SEEK_SET ) → 0

Seeks to a given offset int in the stream according to the value of whence.

IO::SEEK_CUR

Seeks to int plus current position

IO::SEEK_END

Seeks to int plus end of stream (you probably want a negative value for int)

IO::SEEK_SET

Seeks to the absolute location given by int

f = File.new("testfile")

f.seek(-13, IO::SEEK_END) # => 0

f.readline # => "And so on...\n"

set_encoding

  • io.set_encoding(external, internal=external <, options> ) → io
  • io.set_encoding("external-name:internal-name" <, options> ) → io

Sets the external and internal encodings for io. In the first form, encodings can be specified by name (using strings) or as encoding objects. In the second form, the external and internal encoding names are separated by a colon in a string. If present, options specifies the conversion options.

f = File.new("testfile")

f.internal_encoding # => nil

f.external_encoding # => #<Encoding:UTF-8>

f.set_encoding("ascii-8bit:iso-8859-1") # => #<File:testfile>

f.internal_encoding # => #<Encoding:ISO-8859-1>

f.external_encoding # => #<Encoding:ASCII-8BIT>

stat

  • io.stat →stat

Returns status information for io as an object of type File::Stat.

f = File.new("testfile")

s = f.stat

"%o" % s.mode # => "100644"

s.blksize # => 4096

s.atime # => 2013-05-27 12:32:23 -0500

sync

  • io.sync → true or false

Returns the current sync mode of io. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered by Ruby. See also IO#fsync.

sync=

  • io.sync = true or falsetrue or false

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

sysread

  • io.sysread(int <, buffer> ) → string

Reads int bytes from io using a low-level read and returns them as a string. If buffer (a string) is provided, input is read directly in to it. Do not mix with other methods that read from io, or you may get unpredictable results. Raises SystemCallError on error and EOFError at the end of the file.

f = File.new("testfile")

f.sysread(16) # => "This is line one"

str = "cat"

f.sysread(10, str) # => "\nThis is l"

str # => "\nThis is l"

sysseek

  • io.sysseek(offset, whence=SEEK_SET ) → int

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."

syswrite

  • io.syswrite(string ) → int

Writes the given string to io using a low-level write. Returns the number of bytes written. Do not mix with other methods that write to io, or you may get unpredictable results. Raises SystemCallError on error.

f = File.new("out", "w")

f.syswrite("ABCDEF") # => 6

tell

  • io.tell →int

Synonym for IO#pos.

to_i

  • io.to_i →int

Synonym for IO#fileno.

to_io

  • io.to_io →io

Returns io.

tty?

  • io.tty? → true or false

Synonym for IO#isatty.

ungetbyte

  • io.ungetbyte(string or int ) → nil

Pushes back one or more bytes onto io, such that a subsequent buffered read will return them. Has no effect with unbuffered reads (such as IO#sysread).

f = File.new("testfile") # => #<File:testfile>

c = f.getbyte # => 84

f.ungetbyte(c) # => nil

f.getbyte # => 84

f.ungetbyte("cat") # => nil

f.getbyte # => 99

f.getbyte # => 97

ungetc

  • io.ungetc(string ) → nil

Pushes back one or more characters onto io, such that a subsequent buffered read will return them. Has no effect with unbuffered reads (such as IO#sysread).

# encoding: utf-8

f = File.new("testfile") # => #<File:testfile>

c = f.getc # => "T"

f.ungetc(c) # => nil

f.getc # => "T"

f.ungetc("∂og") # => nil

f.getc # => "∂"

f.getc # => "o"

write

  • io.write(string ) → int

Writes the given string to io. 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

write_nonblock

  • io.write_nonblock(string ) → int

Writes the given string to io after setting io into nonblocking mode. 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. Your application should expect to receive errors typical of nonblocking I/O (including EAGAIN and EINTR).

Module Kernel

The Kernel module is included by class Object, so its methods are available in every Ruby object. The Kernel methods are documented in class Object.

Module Marshal

The marshaling library converts collections of Ruby objects into a byte stream, allowing them to be stored outside the currently active script. This data may subsequently be read and the original objects reconstituted. Marshaling is described in Section 25.7, Marshaling and Distributed Ruby. Also see the YAML library.

Marshaled data has major and minor version numbers stored along with the object information. In normal use, marshaling can load only data written with the same major version number and an equal or lower minor version number. If Ruby’s “verbose” flag is set (normally using -d, -v, -w, or --verbose), the major and minor numbers must match exactly. Marshal versioning is independent of Ruby’s version numbers. You can extract the version by reading the first two bytes of marshaled data.

Some objects cannot be dumped: if the objects to be dumped include bindings, procedure or method objects, instances of class IO, or singleton objects, or if you try to dump anonymous classes or modules, a TypeError will be raised.

If your class has special serialization needs (for example, if you want to serialize in some specific format) or if it contains objects that would otherwise not be serializable, you can implement your own serialization strategy using the instance methods marshal_dump and marshal_load . If an object to be marshaled responds to marshal_dump , that method is called instead of _dump . marshal_dump can return an object of any class (not just a string). A class that implements marshal_dump must also implement marshal_load , which is called as an instance method of a newly allocated object and passed the object originally created by marshal_dump .

The following code uses this to store a Time object in the serialized version of an object. When loaded, this object is passed to marshal_load , which converts this time to a printable form, storing the result in an instance variable.

class TimedDump

attr_reader :when_dumped

attr_accessor :other_data

def marshal_dump

[ Time.now, @other_data ]

end

def marshal_load(marshal_data)

@when_dumped = marshal_data[0].strftime("%I:%M%p")

@other_data = marshal_data[1]

end

end

t = TimedDump.new

t.other_data = "wibble"

t.when_dumped # => nil

str = Marshal.dump(t)

newt = Marshal.load(str)

newt.when_dumped # => "12:32PM"

newt.other_data # => "wibble"

Constants

MAJOR_VERSION

Major part of marshal format version number

MINOR_VERSION

Minor part of marshal format version number

Marshal: Module methods

dump

  • dump(obj <, io> , limit=-1 ) → io

Serializes obj and all descendent objects. If io is specified, the serialized data will be written to it; otherwise, the data will be returned as a String. If limit is specified, the traversal of subobjects will be limited to that depth. If the limit is negative, no checking of depth will be performed.

class Klass

def initialize(str)

@str = str

end

def say_hello

@str

end

end

o = Klass.new("hello\n")

data = Marshal.dump(o)

obj = Marshal.load(data)

obj.say_hello # => "hello\n"

load

  • load(from <, proc> ) → obj

Returns the result of converting the serialized data in from into a Ruby object (possibly with associated subordinate objects). from may be either an instance of IO or an object that responds to to_str . If proc is specified, it will be passed each object as it is deserialized.

restore

  • restore(from <, proc> ) → obj

A synonym for Marshal.load.

Class MatchData < Object

All pattern matches set the special variable $~ to a MatchData object containing information about the match. The methods Regexp#match and Regexp.last_match also return a MatchData object. The object encapsulates all the results of a pattern match, results normally accessed through the special variables $&, $’, $‘, $1, $2, and so on—see the list for details.

MatchData: Instance methods

[ ]

  • match[i] →string
  • match[name] →string
  • match[start,length] → array
  • match[range] →array

Match Reference—MatchData acts as an array and/or hash and may be accessed using the normal indexing techniques. Numeric indices return the captures at the corresponding position in the regular expression (starting at 1), and symbol indices return the corresponding named capture.match[0] is equivalent to the special variable $& and returns the entire matched string. See also MatchData#values_at.

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m[0] # => "HX1138"

m[1, 2] # => ["H", "X"]

m[1..3] # => ["H", "X", "113"]

m[-3, 2] # => ["X", "113"]

m = /..(?<digit_prefix>\d+)\d/.match("THX1138.")

m[:digit_prefix] # => "113"

begin

  • match.begin(n ) → int
  • match.begin(name ) → int

Returns the offset in the original string of the start of the nth capture or the named capture.

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m.begin(0) # => 1

m.begin(2) # => 2

m = /..(?<digit_prefix>\d+)\d/.match("THX1138.")

m.begin(:digit_prefix) # => 3

captures

  • match.captures →array

Returns the array of all the matching groups. Compare to MatchData#to_a, which returns both the complete matched string and all the matching groups.

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m.captures # => ["H", "X", "113", "8"]

captures is useful when extracting parts of a match in an assignment.

f1, f2, f3 = /(.)(.)(\d+)(\d)/.match("THX1138.").captures

f1 # => "H"

f2 # => "X"

f3 # => "113"

end

  • match.end(n ) → int
  • match.end(name ) → int

Returns the offset in the original string of the end of the nth capture or the named capture.

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m.end(0) # => 7

m.end(2) # => 3

m = /..(?<digit_prefix>\d+)\d/.match("THX1138.")

m.end(:digit_prefix) # => 6

length

  • match.length →int

Returns the number of elements in the match array.

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m.length # => 5

m.size # => 5

names

  • match.names →array

Returns the list of named captures in the regular expression that created match.

m = /(?<prefix>[A-Z]+)(?<hyphen>-?)(?<digits>\d+)/.match("THX1138.")

m.names # => ["prefix", "hyphen", "digits"]

m.captures # => ["THX", "", "1138"]

m[:prefix] # => "THX"

offset

  • match.offset(n ) → array
  • match.offset(name ) → array

Returns an array containing the beginning and ending offsets of the nth or named capture.

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m.offset(0) # => [1, 7]

m.offset(4) # => [6, 7]

m = /..(?<digit_prefix>\d+)\d/.match("THX1138.")

m.offset(:digit_prefix) # => [3, 6]

post_match

  • match.post_match →string

Returns the portion of the original string after the current match. (Same as the special variable $’.)

m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")

m.post_match # => ": The Movie"

pre_match

  • match.pre_match →string

Returns the portion of the original string before the current match. (Same as $‘.)

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m.pre_match # => "T"

regexp

  • match.regexp →a_regexp

Returns the regexp object for the regular expression that created match.

m = /(.)(.)(\d+)(\d)/.match("THX1138: The Movie")

m.regexp # => /(.)(.)(\d+)(\d)/

size

  • match.size →int

A synonym for MatchData#length.

string

  • match.string →string

Returns a frozen copy of the string passed in to match.

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m.string # => "THX1138."

to_a

  • match.to_a →array

Returns the array of matches. Unlike MatchData#captures, returns the full string matched.

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m.to_a # => ["HX1138", "H", "X", "113", "8"]

to_s

  • match.to_s →string

Returns the entire matched string.

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m.to_s # => "HX1138"

values_at

  • match.values_at(<index>* ) → array

Returns the matches corresponding to the given indices.

m = /(.)(.)(\d+)(\d)/.match("THX1138.")

m.values_at(3,1,2) # => ["113", "H", "X"]

m.values_at(0, 4) # => ["HX1138", "8"]

Module Math

The Math module contains module methods for basic trigonometric and transcendental functions. See class Float for a list of constants that define Ruby’s floating-point accuracy.

Constants

E

An approximation of e (base of natural logarithms)

PI

An approximation of π

Math: Module methods

acos

  • Math.acos(x ) → float

Computes the arc cosine of x. Returns 0..π.

acosh

  • Math.acosh(x ) → float

Computes the inverse hyperbolic cosine of x.

asin

  • Math.asin(x ) → float

Computes the arc sine of x. Returns -π/2..π/2.

asinh

  • Math.asinh(x ) → float

Computes the inverse hyperbolic sine of x.

atan

  • Math.atan(x ) → float

Computes the arc tangent of x. Returns -π/2..π/2.

atanh

  • Math.atanh(x ) → float

Computes the inverse hyperbolic tangent of x.

atan2

  • Math.atan2(y, x ) → float

Computes the arc tangent given y and x. Returns -π..π.

cbrt

  • Math.cbrt(numeric ) → float

Returns the cube root of numeric.

cos

  • Math.cos(x ) → float

Computes the cosine of x (expressed in radians). Returns -1..1.

cosh

  • Math.cosh(x ) → float

Computes the hyperbolic cosine of x (expressed in radians).

erf

  • Math.erf(x ) → float

Returns the error function of x.

erfc

  • Math.erfc(x ) → float

Returns the complementary error function of x.

exp

  • Math.exp(x ) → float

Returns ex.

frexp

  • Math.frexp(numeric ) → [ fraction, exponent ]

Returns the normalized fraction (a Float) and exponent (a Fixnum) of numeric.

fraction, exponent = Math.frexp(1234) # => [0.6025390625, 11]

fraction * 2**exponent # => 1234.0

gamma

  • Math.gamma(x ) → float

Returns the gamma function. For integral x, gamma(x) approximates factorial(x-1).

Math.gamma(2) # => 1.0

Math.gamma(3) # => 2.0

Math.gamma(4) # => 6.0

Math.gamma(10.34) # => 784993.6091493163

hypot

  • Math.hypot(x, y ) → float

Returns sqrt(x2 + y2), the hypotenuse of a right-angled triangle with sides x and y.

Math.hypot(3, 4) # => 5.0

ldexp

  • Math.ldexp(float, n ) → float

Returns the value of float × 2n.

fraction, exponent = Math.frexp(1234)

Math.ldexp(fraction, exponent) # => 1234.0

lgamma

  • Math.lgamma(x ) → [ float, sign ]

The first element of the returned array is the natural logarithm of the absolute value of the gamma function of x. The second value is -1 if the gamma function returned a negative number, +1 otherwise.

log

  • Math.log(numeric <, base=E> ) → float

Returns logarithm of numeric. With no base parameter, returns the natural logarith.

log10

  • Math.log10(numeric ) → float

Returns the base 10 logarithm of numeric.

log2

  • Math.log2(numeric ) → float

Returns the base 2 logarithm of numeric.

sin

  • Math.sin(numeric ) → float

Computes the sine of numeric (expressed in radians). Returns -1..1.

sinh

  • Math.sinh(float ) → float

Computes the hyperbolic sine of numeric (expressed in radians).

sqrt

  • Math.sqrt(float ) → float

Returns the non-negative square root of numeric. Raises ArgError if numeric is less than zero.

tan

  • Math.tan(float ) → float

Returns the tangent of numeric (expressed in radians).

tanh

  • Math.tanh(float ) → float

Computes the hyperbolic tangent of numeric (expressed in radians).

Class Method < Object

Method objects are created by Object#method. They are associated with a particular object (not just with a class). They may be used to invoke the method within the object and as a block associated with an iterator. They may also be unbound from one object (creating an UnboundMethod) and bound to another.

def square(n)

n*n

end

meth = self.method(:square)

meth.call(9) # => 81

[ 1, 2, 3 ].collect(&meth) # => [1, 4, 9]

Method: Instance methods

[ ]

  • meth[<args>* ] → object

Synonym for Method#call.

==

  • meth== othertrue or false

Returns true if meth is the same method as other.

def fred()

puts "Hello"

end

alias bert fred # => nil

m1 = method(:fred)

m2 = method(:bert)

m1 == m2 # => true

arity

  • meth.arity →fixnum

Returns a non-negative integer for methods that take a fixed number of arguments. For Ruby methods that take a variable number of arguments, returns -n-1, where n is the number of required arguments. For methods written in C, returns -1 if the call takes a variable number of arguments. See also Method#parameters.

class C

def one; end

def two(a); end

def three(*a); end

def four(a, b); end

def five(a, b, *c); end

def six(a, b, *c, &d); end

end

c = C.new

c.method(:one).arity # => 0

c.method(:two).arity # => 1

c.method(:three).arity # => -1

c.method(:four).arity # => 2

c.method(:five).arity # => -3

c.method(:six).arity # => -3

"cat".method(:size).arity # => 0

"cat".method(:replace).arity # => 1

"cat".method(:squeeze).arity # => -1

"cat".method(:count).arity # => -1

call

  • meth.call(<args>* ) → object

Invokes the meth with the specified arguments, returning the method’s return value.

m = 12.method("+")

m.call(3) # => 15

m.call(20) # => 32

eql?

  • meth.eql?(other) → true or false

Returns true if meth is the same method as other.

def fred()

puts "Hello"

end

alias bert fred # => nil

m1 = method(:fred)

m2 = method(:bert)

m1.eql?(m2) # => true

name

  • meth.name →string

Returns the name of the method meth.

method = "cat".method(:upcase)

method.name # => :upcase

owner

  • meth.owner →module

Returns the class or module in which meth is defined.

method = "cat".method(:upcase)

method.owner # => String

parameters

  • meth.parameters →array

Returns an array describing the parameters taken by the method. Each entry in the array is itself an array. The first entry of each subarray contains the role of the parameter (:req for required, :opt for optional, :rest for a splat parameter, and :block for a block). If the parameter has a name, it will be the second entry in the subarray.

def m(a, b=1, *c, &d)

end

method(:m).parameters # => [[:req, :a], [:opt, :b], [:rest, :c], [:block, :d]]

receiver

  • meth.receiver →obj

Returns the object on which meth is defined.

method = "cat".method(:upcase)

method.receiver # => "cat"

source_location

  • meth.source_location → [filename, lineno ] or nil

Returns the source filename and line number where meth was defined or nil if self was not defined in Ruby source.

internal_method = "cat".method(:upcase)

internal_method.source_location # => nil

require 'set'

set = Set.new

ruby_method = set.method(:clear)

ruby_method.source_location[0] # => "/Users/dave/.rvm/rubies/ruby-2.0.0-p0/lib/r

# .. uby/2.0.0/set.rb"

ruby_method.source_location[1] # => 131

to_proc

  • meth.to_proc →prc

Returns a Proc object corresponding to this method. Because to_proc is called by the interpreter when passing block arguments, method objects may be used following an ampersand to pass a block to another method call. See the example at the start of this section.

unbind

  • meth.unbind → unbound_method

Dissociates meth from its current receiver. The resulting UnboundMethod can subsequently be bound to a new object of the same class (see UnboundMethod).

Class Module < Object

Subclasses are:

Class

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, and instance methods may not. See also Module#module_function.

In the descriptions that follow, the parameter symbol refers to a name, 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 # => [:CONST, :DomainError, :PI, :E]

Mod.instance_methods # => [:meth]

Module: Class methods

constants

  • Module.constants →array
  • Module.constants(include_parents ) → array

With no argument, returns a list of the top-level constants in the interpreter. With one argument, returns the constants defined in class Module (and its parents if the argument is true). This somewhat obscure interface is because Module is a kind of Class, and Class is a subclass of Module. The first form of call is a true call to the class method constants , while the second form actually proxies to the instance method form (see Module#constants later in this section).

module Mixin

CONST_MIXIN = 1

end

class Module

include Mixin

SPURIOUS_CONSTANT = 2

end

Module.constants.sort[1..3] # => [:ARGV, :ArgumentError, :Array]

Module.constants.include? :CONST_MIXIN # => false

Module.constants(false) # => [:SPURIOUS_CONSTANT]

Module.constants(true) # => [:SPURIOUS_CONSTANT, :CONST_MIXIN]

nesting

  • Module.nesting →array

Returns the list of modules nested at the point of call.

module M1

module M2

nest = Module.nesting

p nest

p nest[0].name

end

end

Produces:

[M1::M2, M1]

"M1::M2"

new

  • Module.new →mod
  • Module.new { |mod| … } →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: Instance methods

<, <=, ==, >, >=

  • modrelop moduletrue, false or nil

Hierarchy Query—One module is considered greater than another if it is included in (or is a parent class of) the other module. The other operators are defined accordingly. If there is no relationship between the modules, all operators return nil.

module Mixin

end

module Parent

include Mixin

end

module Unrelated

end

Parent > Mixin # => false

Parent < Mixin # => true

Parent <= Parent # => true

Parent < Unrelated # => nil

Parent > Unrelated # => nil

<=>

  • mod<=> other_mod → -1, 0, +1

Comparison—Returns -1 if mod includes other_mod, 0 if mod is the same module as other_mod, and +1 if mod is included by other_mod or if mod has no relationship with other_mod.

===

  • mod=== objtrue or false

Case Equality—Returns true if obj is an instance of mod or one of mod’s descendents. Of limited use for modules but can be used in case statements to test objects by class.

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]

autoload

  • mod.autoload(name, file_name ) → nil

Registers file_name to be loaded (using Object#require) the first time that module name (which may be a String or a Symbol) is accessed in the namespace of mod. Note that the autoloaded file is evaluated in the top-level context. In this example, module_b.rb contains the following:

module A::B # in module_b.rb

def doit

puts "In Module A::B"

end

module_function :doit

end

Other code can then include this module automatically.

module A

autoload(:B, "module_b")

end

A::B.doit # autoloads "module_b"

Produces:

In Module A::B

autoload?

  • mod.autoload?(name ) → file_name or nil

Returns the name of the file that will be autoloaded when the string or symbol name is referenced in the context of mod or returns nil if there is no associated autoload.

module A

autoload(:B, "module_b")

end

A.autoload?(:B) # => "module_b"

A.autoload?(:C) # => nil

class_eval

  • mod.class_eval(string <, file_name line_number> ) → obj
  • mod.class_eval { … } →obj

Synonym for Module#module_eval.

class_exec

  • mod.class_exec(<args>+ ) { |args| … } → obj

Synonym for Module#module_exec.

class_variable_defined?

  • mod.class_variable_defined?(name ) → true or false

Returns true if the named class variable is defined in mod. The two @ signs are a required part of the name.

class One

@@var1 = "wibble"

end

One.class_variable_defined?(:@@var1) # => true

One.class_variable_defined?(:@@var2) # => false

class_variable_get

  • mod.class_variable_get(name ) → obj

Returns the value of the named class variable. The two @ signs must appear in the name.

class One

@@var1 = "wibble"

end

One.class_variable_get(:@@var1) # => "wibble"

One.class_variable_get("@@var1") # => "wibble"

class_variable_set

  • mod.class_variable_set(name, value ) → value

Sets the value of the named class variable. The two @ signs must appear in the name.

class One

@@var1 = "wibble"

end

One.class_variable_set(:@@var1, 99) # => 99

One.class_variable_get("@@var1") # => 99

class_variables

  • mod.class_variables →array

Returns an array of the names of class variables in mod. (As of Ruby 1.9, class variables are no longer shared with child classes, so this listing is restricted to the class variables defined in mod.)

class One

@@var1 = 1

end

class Two < One

@@var2 = 2

end

One.class_variables # => [:@@var1]

Two.class_variables # => [:@@var2, :@@var1]

const_defined?

  • mod.const_defined?(symbol <search_parents=true> ) → true or false

Returns true if a constant with the given name is defined by mod or the parents of mod (if the second parameter is true).

Math.const_defined? "PI" # => true

const_get

  • mod.const_get(symbol ) → obj

Returns the value of the named constant in mod. Ruby 2.0 allows this name to be qualified by one or more module names.«2.0»

Math.const_get :PI # => 3.141592653589793

Object.const_get("Math::PI") # => 3.141592653589793

const_missing

  • mod.const_missing(symbol ) → obj

Invoked when a reference is made to an undefined constant in mod. It is passed a symbol for the undefined constant and returns a value to be used for that constant. The following code is very poor style. If a reference is made to an undefined constant, it attempts to load a file whose name is the lowercase version of the constant (thus, class Fred is assumed to be in file fred.rb). If found, it returns the value of the loaded class. It therefore implements a perverse kind of autoload facility.

def Object.const_missing(name)

@looked_for ||= {}

str_name = name.to_s

raise "Class not found: #{name}" if @looked_for[str_name]

@looked_for[str_name] = 1

file = str_name.downcase

require file

klass = const_get(name)

return klass if klass

raise "Class not found: #{name}"

end

const_set

  • mod.const_set(symbol, 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.142857142857143

Math::HIGH_SCHOOL_PI - Math::PI # => 0.0012644892673496777

constants

  • mod.constants(include_parents = true ) → array

Returns an array of the names of the constants accessible in mod. If the parameter is true, this includes the names of constants in any included modules.

IO.constants(false) # => [:WaitReadable, :WaitWritable, :SEEK_SET, :SEEK_CUR,

# .. :SEEK_END]

# Now include stuff defined in module File::Constants

IO.constants(true)[1,6] # => [:WaitWritable, :SEEK_SET, :SEEK_CUR, :SEEK_END,

# .. :RDONLY, :WRONLY]

include?

  • mod.include?(other_mod ) → true or false

Returns true if other_mod 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

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]

instance_method

  • mod.instance_method(symbol ) → unbound_method

Returns an UnboundMethod representing the given instance method in mod.

class Interpreter

def do_a() print "there, "; end

def do_d() print "Hello "; end

def do_e() print "!\n"; end

def do_v() print "Dave"; end

Dispatcher = {

'a' => instance_method(:do_a),

'd' => instance_method(:do_d),

'e' => instance_method(:do_e),

'v' => instance_method(:do_v)

}

def interpret(string)

string.each_char {|ch| Dispatcher[ch].bind(self).call }

end

end

interpreter = Interpreter.new

interpreter.interpret('dave')

Produces:

Hello there, Dave!

instance_methods

  • mod.instance_methods(inc_super=true ) → array

Returns an array containing the names of public and protected 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 true, the methods in mod and mod’s superclasses are returned. When called with a module as a receiver or with a parameter that is false, the instance methods in mod 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 # => 56

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_eval

  • mod.module_eval(string <, file_name line_number> ) → obj
  • mod.module_eval { … } →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 file_name and line_number 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 `<main>': undefined local variable

or method `code' for Thing:Class

module_exec

  • mod.module_exec(<args>+ ) { |args| … } → obj

Behaves the same as the block form for Module#module_eval, except any parameters passed to the method are in turn passed to the block. This gives you a way of passing in values that would otherwise not be in scope in the block (because self is changed).

class Thing

end

name = :new_instance_variable

Thing.module_exec(name) do |iv_name|

attr_accessor iv_name

end

t = Thing.new

t.new_instance_variable = "wibble"

p t

Produces:

#<Thing:0x007f9b01847fa8 @new_instance_variable="wibble">

name

  • mod.name →string

Returns the name of the module mod.

private_class_method

  • mod.private_class_method(<symbol>+ ) → nil

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

private_constant

  • mod.private_constant(<symbol>+ ) → mod

Makes the given constants (which must already have been defined) private to the module. A private constant cannot be referenced using the module name as a scope, so they effectively can only be accessed within the context of the module itself.

module A

B = "my constant"

private_constant :B

puts "Inside A, B = #{B.inspect}"

end

puts "Outside A, A::B = #{A::B.inspect}"

Produces:

Inside A, B = "my constant"

prog.rb:7:in `<main>': private constant A::B referenced (NameError)

private_instance_methods

  • mod.private_instance_methods(inc_super=true ) → array

Returns a list of the private instance methods defined in mod. If the optional parameter is true, 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]

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

protected_instance_methods

  • mod.protected_instance_methods(inc_super=true ) → array

Returns a list of the protected instance methods defined in mod. If the optional parameter is true, the methods of any ancestors are included.

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

public_class_method

  • mod.public_class_method(<symbol>+ ) → nil

Makes a list of existing class methods public.

public_constant

  • mod.public_constant(<symbol>+ ) → mod

Makes the given constants (which must already have been defined) public, overriding the effect of a previous call to privante_constant .

module A

B = "my constant"

private_constant :B

puts "Inside A, B = #{B.inspect}"

public_constant :B

end

puts "Outside A, A::B = #{A::B.inspect}"

Produces:

Inside A, B = "my constant"

Outside A, A::B = "my constant"

public_instance_method

  • mod.public_instance_method(symbol ) → unbound_method

Returns an UnboundMethod representing the given public instance method in mod. See also Module#instance_method, which ignores scope.

class Test

def method_a; end

private

def method_b; end

end

puts "method_a is #{Test.public_instance_method(:method_a)}"

puts "method_b is #{Test.public_instance_method(:method_b)}"

Produces:

from prog.rb:7:in `<main>'

method_a is #<UnboundMethod: Test#method_a>

prog.rb:7:in `public_instance_method': method `method_b' for class `Test' is

private (NameError)

public_instance_methods

  • mod.public_instance_methods(inc_super=true ) → array

Returns a list of the public instance methods defined in mod. If the optional parameter is true, the methods of any ancestors are included.

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

remove_class_variable

  • remove_class_variable(symbol ) → obj

Removes the definition of the symbol, returning that variable’s value. Prior to Ruby 1.9, this method was private.

class Dummy

@@var = 99

end

Dummy.class_eval { p defined? @@var }

puts Dummy.remove_class_variable(:@@var)

Dummy.class_eval { p defined? @@var }

Produces:

prog.rb:4: warning: class variable access from toplevel

nil

prog.rb:6: warning: class variable access from toplevel

99

nil

Module: Private instance methods

alias_method

  • alias_method(new_id, old_id ) → mod

Makes new_id a new copy of the method old_id. 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

append_features

  • append_features(other_mod ) → mod

When this module is included in another, Ruby calls append_features in this module, passing it the receiving module in other_mod. Ruby’s default implementation is to add the constants, methods, and module variables of this module to other_mod if this module has not already been added toother_mod or one of its ancestors. Prior to Ruby 1.8, user code often redefined append_features , added its own functionality, and then invoked super to handle the real include. Now you should instead implement the method Module#included.

attr

  • attr(<symbol>+ ) → nil

An alias for Module#attr_reader (as of Ruby 1.9).

attr_accessor

  • attr_accessor(<symbol>+ ) → nil

Creates a reader and a writer method for each symbol passed as an argument. These methods provide access to the underlying instance variables of the name name (with a leading @ sign).

class Test

attr_accessor :name, :likes

def initialize(name, likes)

@name = name

@likes = likes

end

end

d = Test.new("Dave", "Ruby")

d.name = "Chad"

d.name # => "Chad"

d.likes # => "Ruby"

attr_reader

  • attr_reader(<symbol>+ ) → nil

Creates instance variables and corresponding methods that return their values.

class Test

attr_reader :name, :likes

def initialize(name, likes)

@name = name

@likes = likes

end

end

d = Test.new("Dave", "Ruby")

d.name # => "Dave"

d.likes # => "Ruby"

attr_writer

  • attr_writer(<symbol>+ ) → nil

Creates an accessor method to allow assignment to the attribute symbol.id2name.

class Test

attr_writer :name, :likes

def initialize(name, likes)

@name = name

@likes = likes

end

end

d = Test.new("Dave", "Ruby")

d.name = "Chad"

d # => #<Test:0x007fc52210f8a8 @name="Chad", @likes="Ruby">

define_method

  • define_method(symbol, method ) → method
  • define_method(symbol ) { … } → proc

Defines an instance method in the receiver. The method parameter can be a Proc, a Method, or an UnboundMethod object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval . This is tricky to demonstrate because define_method is private. (This is why we resort to the send hack in this example.) See also Object#define_singleton_method.

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

b = B.new

b.barney

b.wilma

b.create_method(:betty) { p self }

b.betty

Produces:

In Fred

Charge it!

#<B:0x007fb6bb846600>

Note that it is possible to define methods with names that are not valid if you were to use the def keyword. These methods cannot be invoked directly.

class Silly

define_method("Oh !@!#^!") { "As Snoopy says" }

end

Silly.new.send("Oh !@!#^!") # => "As Snoopy says"

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

extended

  • extended(other_mod )

Callback invoked whenever the receiver is used to extend an object. The object is passed as a parameter. This should be used in preference to Module#extend_object if your code wants to perform some action when a module is used to extend an object.

module A

def A.extended(obj)

puts "#{self} extending '#{obj}'"

end

end

"cat".extend(A)

Produces:

A extending 'cat'

include

  • include(<other_mod>+ ) → mod

Includes the listed modules in self. Typically used to make the instance methods in the included modules available in the receiver. Equivalent to the following code:

def include(*modules)

modules.reverse_each do |mod|

mod.append_features(self) # make the methods available

mod.included(self) # invoke a callback

end

end

See also Module#prepend.«2.0»

included

  • included(other_mod )

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

Produces:

A included in Enumerable

method_added

  • method_added(symbol )

Invoked as a callback whenever a method is added to the receiver.

module Chatty

def Chatty.method_added(id)

puts "Adding #{id.id2name}"

end

def one; end

end

module Chatty

def two; end

end

Produces:

Adding one

Adding two

method_removed

  • method_removed(symbol )

Invoked as a callback whenever a method is removed from the receiver.

module Chatty

def Chatty.method_removed(id)

puts "Removing #{id.id2name}"

end

def one

end

end

module Chatty

remove_method(:one)

end

Produces:

Removing one

method_undefined

  • method_undefined(symbol )

Invoked as a callback whenever a method is undefined in the receiver.

module Chatty

def Chatty.method_undefined(id)

puts "Undefining #{id.id2name}"

end

def one

end

end

module Chatty

undef_method(:one)

end

Produces:

Undefining one

module_function

  • module_function(<symbol>* ) → mod

Creates module functions for the named methods. These functions may be called with the module as a receiver. 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 call_one

one

end

end

Mod.one # => "This is one"

c = Cls.new

c.call_one # => "This is one"

module Mod

def one

"This is the new one"

end

end

Mod.one # => "This is one"

c.call_one # => "This is the new one"

prepend

  • prepend(<other_mod>+ ) → mod

Includes the listed modules in self. Unlike Module#include. if the module contains methods with the same names as those in the including module, the included modules methods take precedence.«2.0»

module Mod

def meth; "In module Mod"; end

end

class Cls1

def meth; "In class Cls1"; end

include Mod

end

class Cls2

def meth; "In class Cls2"; end

prepend Mod

end

See also Module#include.«2.0»

private

  • private(<symbol>* ) → mod

With no arguments, sets the default visibility for subsequently defined methods to private. With arguments, sets the named methods to have private visibility. See “Access Control”.

module Mod

def a; end

def b; end

private

def c; end

private :a

end

Mod.private_instance_methods # => [:a, :c]

protected

  • protected(<symbol>* ) → mod

With no arguments, sets the default visibility for subsequently defined methods to protected. With arguments, sets the named methods to have protected visibility. See “Access Control”.

public

  • public(<symbol>* ) → mod

With no arguments, sets the default visibility for subsequently defined methods to public. With arguments, sets the named methods to have public visibility. See “Access Control”.

refine

  • refine(class ) { … } → refmod

Defines a refinement for the given class. This is activated from the top-level of a source file with the Object#using method, which applies the methods defined in the block to the given class for the remainder of that source file. The tutorial has more information.«2.0» refine returns a special kind of module object that represents the change to be made to the host class.

module SuperUpcase

refine String do

def upcase

"!#{super}!"

end

end

end

puts "wombat".upcase

using SuperUpcase

puts "wombat".upcase

Produces:

WOMBAT

!WOMBAT!

remove_const

  • remove_const(symbol ) → obj

Removes the definition of the given constant, returning that constant’s value. Predefined classes and singleton objects (such as true) cannot be removed.

remove_method

  • remove_method(symbol ) → mod

Removes the method identified by symbol from the current class. For an example, see Module#undef_method.

undef_method

  • undef_method(<symbol>+ ) → mod

Prevents the current class from responding to calls to the named method(s). 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:24:in `<main>': undefined method `hello' for #<Child:0x007fcfa4042ee8>

(NoMethodError)

Class Mutex < Object

A mutex is a semaphore object that can be used to synchronize access to resources shared across threads. We discussed mutexes (and other synchronization mechanisms) in Section 12.4, Mutual Exclusion. Because the code examples tend to be long, we haven’t duplicated them in this library description.

Mutex: Instance methods

lock

  • mutex.lock →mutex

Takes a lock on mutex. Suspends if mutex is already locked by another thread and raises a ThreadError if the mutex is already locked by the calling thread or if called from a trap handler«2.0».

locked?

  • mutex.locked? → true or false

Returns the current locked state of mutex.

owned?

  • mutex.owned? → true or false

Returns true if the mutex is held by the current thread. Experimental in Ruby 2.0«2.0».

sleep

  • mutex.sleep(time | nil ) → seconds_slept

Releases the current thread’s lock on mutex, sleeps for time seconds (or forever if nil is passed), and then regains the lock. Returns the number of seconds actually slept. This may be less than the number requested, so it is wise to check. May not be called from a trap handler«2.0».

synchronize

  • mutex.synchronize { … } →obj

Locks mutex, executes the block, and then unlocks mutex. Returns the value returned by the block. May not be called from a trap handler«2.0».

try_lock

  • mutex.try_lock → true or false

If mutex is not currently locked, locks it and returns true. Otherwise, returns false. (That is, try_lock is like lock , but it will never wait for a mutex to become available.) May not be called from a trap handler«2.0».

unlock

  • mutex.unlock →mutex

Unlock mutex, which must be locked by the current thread. May not be called from a trap handler«2.0».

Class NilClass < Object

The class of the singleton object nil.

NilClass: Instance methods

&

  • nil &obj → false

And—Returns false. Because obj is an argument to a method call, it is always evaluated; there is no short-circuit evaluation in this case.

nil && puts("logical and")

nil & puts("and")

Produces:

and

^

  • nil ^objtrue or false

Exclusive Or—Returns false if obj is nil or false and returns true otherwise.

|

  • nil |objtrue or false

Or—Returns false if obj is nil or false and returns true otherwise.

nil | false # => false

nil | 99 # => true

nil?

  • nil.nil? → true

Always returns true.

rationalize

  • int.rationalize(eps=nil ) → Rational(0)

Returns Rational("0"). The argument is always ignored.

nil.rationalize # => (0/1)

to_a

  • nil.to_a → []

Always returns an empty array.

nil.to_a # => []

to_c

  • nil.to_c → Complex(0,0)

Always returns the origin of the complex plane.

nil.to_c # => (0+0i)

to_f

  • nil.to_f → 0.0

Always returns zero.

nil.to_f # => 0.0

to_h

  • nil.to_h → {}

Always returns an empty hash.«2.0»

nil.to_h # => {}

to_i

  • nil.to_i → 0

Always returns zero.

nil.to_i # => 0

to_r

  • nil.to_r → Rational(0,1)

Always returns zero as a rational number.

nil.to_r # => (0/1)

to_s

  • nil.to_s → ""

Always returns the empty string.

nil.to_s # => ""

Class Numeric < Object

Subclasses are:

Float, Integer

Numeric is the fundamental base type for the abstract class Integer and the concrete number classes Bignum, Complex, Float, Fixnum, and Rational. Many methods in Numeric are overridden in child classes, and Numeric takes some liberties by calling methods in these child classes. Here’s a complete list of the methods defined in all five classes:

Table 20. Methods in the numeric classes

Numeric

Integer

Fixnum

Bignum

Float

Rational

Complex

%

&

*

**

+

+@

-

-@

/

<

<<

<=

<=>

==

===

>

>=

>>

[]

^

abs

abs2

angle

arg

ceil

chr

coerce

conj

conjugate

denominator

div

divmod

downto

eql?

even?

fdiv

finite?

floor

gcd

gcdlcm

i

imag

imaginary

infinite?

integer?

lcm

magnitude

modulo

nan?

next

nonzero?

numerator

odd?

ord

phase

polar

pred

quo

rationalize

real

real?

rect

rectangular

remainder

round

size

step

succ

times

to_c

to_f

to_i

to_int

to_r

to_s

truncate

upto

zero?

|

~

Mixes in

Comparable

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

Numeric: Instance methods

+@

  • +numnum

Unary Plus—Returns the receiver’s value.

-@

  • --numnumeric

Unary Minus—Returns the receiver’s value, negated.

<=>

  • num<=> other → 0 or nil

Returns zero if num equals other and returns nil otherwise.

%

  • num% numericnumeric

Synonym for Numeric#module. Equivalent to num.divmod(numeric)[1].

abs

  • num.abs →numeric

Returns the absolute value of num.

12.abs # => 12

(-34.56).abs # => 34.56

-34.56.abs # => 34.56

abs2

  • num.abs2 →numeric

Returns the square of (the absolute value of) num.

12.abs2 # => 144

(-34.56).abs2 # => 1194.3936

-34.56.abs2 # => 1194.3936

angle

  • num.angle →numeric

For noncomplex numbers, returns π for negative numbers, 0 otherwise. See Complex for more details.

arg

  • num.arg →numeric

Synonym for Numeric#angle.

ceil

  • num.ceil →int

Returns the smallest integer greater than or equal to num. Class Numeric achieves this by converting itself to a Float and then invoking Float#ceil.

1.ceil # => 1

1.2.ceil # => 2

(-1.2).ceil # => -1

(-1.0).ceil # => -1

coerce

  • num.coerce(numeric ) → array

coerce is both an instance method of Numeric and part of a type conversion protocol. When a number is asked to perform an operation and it is passed a parameter of a class different from its own, it must first coerce both itself and that parameter into a common class so that the operation makes sense. For example, in the expression 1 + 2.5, the Fixnum 1 must be converted to a Float to make it compatible with 2.5. This conversion is performed by coerce . For all numeric objects, coerce is straightforward: if numeric is the same type as num, returns an array containing numeric and num. Otherwise, returns an array with both numeric and num represented as Float objects.

1.coerce(2.5) # => [2.5, 1.0]

1.2.coerce(3) # => [3.0, 1.2]

1.coerce(2) # => [2, 1]

If a numeric object is asked to operate on a non-numeric, it tries to invoke coerce on that other object. For example, if you write this:

1 + "2"

then Ruby will effectively execute the code as follows:

n1, n2 = "2".coerce(1)

n2 + n1

In the more general case, this won’t work, because most non-numerics don’t define a coerce method. However, you can use this (if you feel so inclined) to implement part of Perl’s automatic conversion of strings to numbers in expressions.

class String

def coerce(other)

case other

when Integer

begin

return other, Integer(self)

rescue

return Float(other), Float(self)

end

when Float

return other, Float(self)

elsesuper

end

end

end

1 + "2" # => 3

1 - "2.3" # => -1.2999999999999998

1.2 + "2.3" # => 3.5

1.5 - "2" # => -0.5

coerce is discussed in the tutorial.

conj

  • num.conj →num

Synonym for Numeric#conjugate.

conjugate

  • num.conjugate →num

Returns the complex conjugate of num. For noncomplex numbers, returns num.

denominator

  • num.denominator →integer

Returns the denominator of the rational representation of num.

1.denominator # => 1

1.5.denominator # => 2

num = 1.0/3

num.to_r # => (6004799503160661/18014398509481984)

num.denominator # => 18014398509481984

div

  • num.div(numeric ) → int

Uses / to perform division and then converts the result to an integer. Numeric does not define the / operator; this is left to subclasses.

divmod

  • num.divmod(numeric ) → array

Returns an array containing the quotient and modulus obtained by dividing num by numeric. If q,r = x.divmod(y), then q = floor(float(x) / float(y)) and x = q * y + r. The quotient is rounded toward -infinity.

Table 21. Division, modulo, and remainder

a

b

a.divmod(b)

a/b

a.modulo(b)

(a.remainder(b)

The modulo operator % always has the sign of the divisor, whereas remainder has the sign of the dividend.

13

4

[3, 1]

3

1

1

13

-4

[-4, -3]

-4

-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

eql?

  • num.eql?(numeric ) → true or false

Returns true if num and numeric are the same type and have equal values.

1 == 1.0 # => true

1.eql?(1.0) # => false

(1.0).eql?(1.0) # => true

fdiv

  • num.fdiv(numeric ) → numeric

Synonym for Numeric#quo.

floor

  • num.floor →int

Returns the largest integer less than or equal to num. Numeric implements this by converting int to a Float and invoking Float#floor.

1.floor # => 1

(-1).floor # => -1

i

  • num.i → Complex(0,num)

Returns the complex number whose imaginary part is num.

imag

  • num.imag → 0

Synonym for Numeric#imaginary.

imaginary

  • num.image → 0

Returns the imaginary part of num. Always 0 unless num is a complex number.

1.imaginary # => 0

integer?

  • num.integer? → true or false

Returns true if num is an Integer (including Fixnum and Bignum).

magnitude

  • num.magnitude →int or float

Returns the magnitude of num (the distance of num from the origin of the number line). See also Complex#magnitude.

3.magnitude # => 3

-3.0.magnitude # => 3.0

modulo

  • num.modulo(numeric ) → numeric

Equivalent to num.divmod(numeric)[1].

nonzero?

  • num.nonzero? →num or nil

Returns num if num is not zero and returns nil otherwise. This behavior is useful when chaining comparisons.

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"]

numerator

  • num.numerator →integer

Returns the numerator of the rational representation of num.

1.numerator # => 1

1.5.numerator # => 3

num = 1.0/3

num.to_r # => (6004799503160661/18014398509481984)

num.numerator # => 6004799503160661

phase

  • num.phase → [magnitude,angle ]

Returns the phase angle of num. See Complex for more information. For noncomplex numbers, returns 0 if num is nonnegative, π otherwise.

123.phase # => 0

polar

  • num.polar → [magnitude,angle ]

Returns num in polar form. See Complex for more information. For noncomplex numbers, returns [num,0].

123.polar # => [123, 0]

quo

  • num.quo(numeric ) → numeric

Equivalent to Numeric#/ but overridden in subclasses. The intent of quo is to return the most accurate result of division (in context). Thus, 1.quo(2) will equal the rational number 1/2, while 1/2 equals 0.

real

  • num.real →num

Returns the real part of num. Always num unless num is a complex number.

1.real # => 1

1.5.real # => 1.5

real?

  • num.real? → true

All the built-in numeric classes except Complex represent scalar types and hence respond true to real? .

1.real? # => true

1.0.real? # => true

Complex(1,0).real? # => false

rect

  • num.rect → [num, 0 ]

Returns an array containing the real and imaginary components of num. See also Complex#rect.

1.5.rect # => [1.5, 0]

rectangular

  • num.rectangular → [num, 0 ]

Synonym for Numeric#rect.

remainder

  • num.remainder(numeric ) → another_numeric

Returns num - (num/numeric).truncate. See Table 21, Division, modulo, and remainder.

round

  • num.round →int

Rounds num to the nearest integer.

step

  • num.step(end_num, step ) { |i| … } → num
  • num.step(end_num, step ) → enumerator

Invokes block with the sequence of numbers starting at num, incremented by step on each call. The loop finishes when the value to be passed to the block is greater than end_num (if step is positive) or less than end_num (if step is negative). If all the arguments are integers, the loop operates using an integer counter. If any of the arguments are floating-point numbers, all are converted to floats, and the loop is executed floor(n + n*Float::EPSILON)+1 times, where n = (end_num - num)/step. Otherwise, the loop starts at num, uses either the < or > operator to compare the counter against end_num, and increments itself using the + operator. Returns an enumerator if no block is given.

1.step(10, 2) {|i| print i, " " }

Produces:

1 3 5 7 9

Math::E.step(Math::PI, 0.2) {|f| print f, " " }

Produces:

2.718281828459045 2.9182818284590453 3.118281828459045

to_c

  • num.to_c →complex

Returns num as a complex number.

123.to_c # => 123+0i

to_int

  • num.to_int →int

Invokes the child class’s to_i method to convert num to an integer.

truncate

  • num.truncate →int

Returns num truncated to an integer.

zero?

  • num.zero? → true or false

Returns true if num has a zero value.

Class Object < BasicObject

Subclasses are:

Object is the parent class of (almost) all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden.

Object mixes in the Kernel module, making the built-in kernel functions globally accessible. Although the instance methods of Object are defined by the Kernel module, we have chosen to document them here for clarity.

In the descriptions that follow, the parameter symbol refers to a name, which is either a quoted string or a symbol (such as :name).

Object: Instance methods

===

  • obj=== other_objtrue or false

Case Equality—A synonym for Object#== but typically overridden by descendents to provide meaningful semantics in case statements.

<=>

  • obj<=> other_obj → 0 or nil

Comparison—For objects, returns 0 if other_obj is the same object as, or is equal to, obj. Otherwise, returns nil (which should be interpreted to mean that there’s no meaning to the comparison). Overridden by subclasses that have comparison semantics.

=~

  • obj=~ other_obj → nil

Pattern Match—Overridden by descendents (notably Regexp and String) to provide meaningful pattern-match semantics.

!~

  • obj!~ other_obj → !(obj =~ other_obj)

Opposite of =~ .

class

  • obj.class →klass

Returns the class object of obj. This method must always be called with an explicit receiver, because class is also a reserved word in Ruby.

1.class # => Fixnum

self.class # => Object

clone

  • obj.clone →other_obj

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj, along with any associated singleton class. See also the discussion under Object#dup.

class Klass

attr_accessor :str

end

s1 = Klass.new # => #<Klass:0x007fc1bb10ee90>

s1.str = "Hello" # => "Hello"

s2 = s1.clone # => #<Klass:0x007fc1bb10e940 @str="Hello">

s2.str[1,4] = "i" # => "i"

s1.inspect # => "#<Klass:0x007fc1bb10ee90 @str=\"Hi\">"

s2.inspect # => "#<Klass:0x007fc1bb10e940 @str=\"Hi\">"

define_singleton_method

  • obj.define_singleton_method(symbol, method ) → method
  • obj.define_singleton_method(symbol ) { … } → proc

Defines a singleton method in the receiver. The method parameter can be a Proc, Method, or UnboundMethod object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval . See also Module#define_method.

a = "cat"

a.define_singleton_method(:speak) do

"#{self} says miaow"

end

a.speak # => "cat says miaow"

define_singleton_method is also useful with Module#class_eval:

class Test

class_eval do

define_method(:one) { puts "instance method" }

define_singleton_method(:two) { puts "class method" }

end

end

t = Test.new

t.one

Test.two

Produces:

instance method

class method

display

  • obj.display(port=$> ) → nil

Prints obj on the given port (default $>). Equivalent to the following:

def display(port=$>)

port.write self

end

For example:

1.display

"cat".display

[ 4, 5, 6 ].display

Produces:

1cat[4, 5, 6]

dup

  • obj.dup →other_obj

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. See also the discussion under Object#clone. In general, dup duplicates just the state of an object, while clone also copies the state, any associated singleton class, and any internal flags (such as whether the object is frozen). The taint status is copied by both dup and clone .

enum_for

  • obj.enum_for(using=:each,<args>+enumerator
  • obj.enum_for(using=:each,<args>+ { |*args| … } → enumerator

Synonym for Object#to_enum.

eql?

  • obj.eql?(other_obj ) → true or false

Returns true if obj and other_obj 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? . This means the following:

1 == 1.0 # => true

1.eql? 1.0 # => false

extend

  • obj.extend(<mod>+ ) → obj

Mix the instance methods from each of the given modules in to obj. See Chapter 24, Metaprogramming for information on how this works. See also Module#extend_object.

module Mod

def hello

"Hello from Mod.\n"

end

end

class Klass

def hello

"Hello from Klass.\n"

end

end

k = Klass.new

k.hello # => "Hello from Klass.\n"

k.extend(Mod) # => #<Klass:0x007f9fe190f208>

k.hello # => "Hello from Mod.\n"

Writing obj.extend(Mod) is basically the same as the following:

class <<obj

include Mod

end

freeze

  • obj.freeze →obj

Prevents further modifications to obj. A RuntimeError will be raised if modification is attempted. You cannot unfreeze a frozen object. See also Object#frozen?.

a = [ "a", "b", "c" ]

a.freeze

a << "z"

Produces:

prog.rb:3:in `<main>': can't modify frozen Array (RuntimeError)

frozen?

  • obj.frozen? → true or false

Returns the freeze status of obj.

a = [ "a", "b", "c" ]

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

a.frozen? # => true

hash

  • obj.hash →fixnum

Generates a Fixnum hash value for obj. This function must have the property that a.eql?(b) implies a.hash == b.hash. The hash value is used by class Hash. Any hash value that exceeds the capacity of a Fixnum will be truncated before being used. For instances of class Object, the hash is also the object_id . This will not always be the case for subclasses.

initialize_clone

  • obj.initialize_clone(other) →other_obj or obj

Invoked as a callback by Object#clone to initialize the cloned object. The default implementation is to call initialize_copy .

initialize_copy

  • obj.initialize_copy(other) →other_obj or obj

Part of the protocol used by Object#dup and #clone , initialize_copy is the fallback method invoked by Object#initialize_clone and #initialize_dup . If you need specialized copy semantics depending on whether clone or dup is called, override those more specific callbacks. If you want common behavior, override initialize_copy .

These methods should copy across any state information that dup and clone cannot copy themselves. For example, in the following code, a and b reference two instances of the container class, but each instance shares a single string object:

class Container

attr_accessor :content

end

a = Container.new

a.content = "cat"

b = a.dup

a.content[1..-1] = "anary"

a.content # => "canary"

b.content # => "canary"

The next example uses initialize_copy to create a new string in the duplicated object.

class Container

attr_accessor :content

def initialize_copy(other)

@content = String.new(other.content)

end

end

a = Container.new

a.content = "cat"

b = a.dup

a.content[1..-1] = "anary"

a.content # => "canary"

b.content # => "cat"

initialize_dup

  • obj.initialize_dup(other) →other_obj or obj

Invoked as a callback by Object#dup to initialize the duplicated object. The default implementation is to call initialize_copy .

inspect

  • obj.inspect →string

Returns a string containing a human-readable representation of obj. For objects of classes written in Ruby, displays the values of instance variables along with the class name if any instance variables exist. Override this in subclasses to change their behavior when inspected.«2.0»

[ 1, 2, 3..4, 'five' ].inspect # => [1, 2, 3..4, "five"]

Time.new.inspect # => 2013-05-27 12:32:34 -0500

class Demo

def initialize; @a, @b = 1, 2; end

end

Demo.new.inspect # => #<Demo:0x007fb6d190f1e8 @a=1, @b=2>

instance_of?

  • obj.instance_of?(klass ) → true or false

Returns true if obj is an instance of the given class. See also Object#kind_of?.

instance_variable_defined?

  • obj.instance_variable_defined?(name ) → true or false

Returns true if the named variable is defined. Note that a common idiom, testing to see whether @fred is nil, is incorrect in two ways: first the variable could be defined but set to nil, and second it will generate a warning if debug mode is enabled.

class Fred

def initialize(p1, p2)

@a, @b = p1, p2

end

end

fred = Fred.new('cat', 99)

fred.instance_variable_defined?(:@a) # => true

fred.instance_variable_defined?("@b") # => true

fred.instance_variable_defined?(:@c) # => false

instance_variable_get

  • obj.instance_variable_get(symbol ) → other_obj

Returns the value of the given instance variable (or throws a NameError exception). The @ part of the variable name should be included for regular instance variables.

class Fred

def initialize(p1, p2)

@a, @b = p1, p2

end

end

fred = Fred.new('cat', 99)

fred.instance_variable_get(:@a) # => "cat"

fred.instance_variable_get("@b") # => 99

instance_variable_set

  • obj.instance_variable_set(symbol, other_obj ) → other_obj

Sets the instance variable names by symbol to other_obj, thereby frustrating the efforts of the class’s author to attempt to provide proper encapsulation.

class Fred

def initialize(p1, p2)

@a, @b = p1, p2

end

end

fred = Fred.new('cat', 99)

fred.instance_variable_set(:@a, 'dog')

fred.inspect # => #<Fred:0x007fcd9b047d40 @a="dog", @b=99>

instance_variables

  • obj.instance_variables →array

Returns an array of instance variable names for the receiver. Note that simply defining an accessor does not create the corresponding instance variable.

class Fred

attr_accessor :a1

def initialize

@iv = 3

end

end

Fred.new.instance_variables # => [:@iv]

is_a?

  • obj.is_a?(klass ) → true or false

Synonym for Object#kind_of?.

kind_of?

  • obj.kind_of?(klass ) → true or false

Returns true if klass is the class of obj or if klass is one of the superclasses of obj or modules included in obj.

module M

end

class A

include M

end

class B < A; end

class C < B; end

b = B.new

b.instance_of? A # => false

b.instance_of? B # => true

b.instance_of? C # => false

b.instance_of? M # => false

b.kind_of? A # => true

b.kind_of? B # => true

b.kind_of? C # => false

b.kind_of? M # => true

method

  • obj.method(symbol ) → meth

Looks up the named method in obj, returning a Method object (or raising NameError). The Method object is a closure, so instance variables and the value of self remain available.

class Demo

def initialize(n)

@iv = n

end

def hello()

"Hello, @iv = #{@iv}"

end

end

k = Demo.new(99)

m = k.method(:hello)

m.call # => "Hello, @iv = 99"

l = Demo.new('Fred')

m = l.method("hello")

m.call # => "Hello, @iv = Fred"

methods

  • obj.methods(regular=true ) → array

If regular is true, returns a list of the names of methods publicly accessible in obj and obj’s ancestors. Otherwise, returns a list of obj’s singleton methods.

class Klass

def my_method; end

end

k = Klass.new

def k.single; end

k.methods[0..6] # => [:single, :my_method, :nil?, :===, :=~, :!~, :eql?]

k.methods.length # => 56

k.methods(false) # => [:single]

nil?

  • obj.nil? → true or false

All objects except nil return false.

object_id

  • obj.object_id →fixnum

Returns an integer identifier for obj. The same number will be returned on all calls to object_id for a given object, and no two active objects will share an ID. Object#object_id is a different concept from the :name notation, which returns the symbol ID of name. Replaces the deprecated Object#id.

private_methods

  • obj.private_methods →array

Returns a list of private methods accessible within obj. This will include the private methods in obj’s ancestors, along with any mixed-in module functions.

protected_methods

  • obj.protected_methods →array

Returns the list of protected methods accessible to obj.

public_method

  • obj.public_method(symbol ) → meth

Looks up the named public method in obj, returning a Method object (or raising NameError if the method is not found or if it is found but not public).

class Demo

def initialize(n)

@iv = n

end

def hello()

puts "Hello, @iv = #{@iv}"

end

end

k = Demo.new(99)

m = k.public_method(:hello)

m.call

l = Demo.new('Fred')

m = l.public_method(:initialize)

m.call

Produces:

from prog.rb:15:in `<main>'

Hello, @iv = 99

prog.rb:15:in `public_method': method `initialize' for class `Demo' is private

(NameError)

public_methods

  • obj.public_methods →array

Synonym for Object#methods.

public_send

  • obj.public_send(name, <args>+ ) → obj

Invokes obj’s public method name, passing in any arguments. Returns the value returned by the method. See also send , which will also call private and protected methods.

respond_to?

  • obj.respond_to?(symbol, include_priv=false ) → true or false

Returns true if obj responds to the given method. Private and protected«2.0» methods are included in the search only if the optional second parameter evaluates to true.

respond_to_missing?

  • obj.respond_to_missing?(symbol, include_priv=false ) → true or false

A callback invoked by the interpreter if respond_to? is called and does not find a method. This allows classes to indicate that they implement methods via method_missing .

class Example

def regular

end

def method_missing(name, *args, &block)

if name == :dynamic

# do something

else

super

end

end

def respond_to_missing?(name, include_priv)

name == :dynamic

end

end

ex = Example.new

ex.respond_to?(:regular) # => true

ex.respond_to?(:dynamic) # => true

ex.respond_to?(:other) # => false

send

  • obj.send(symbol <, args>* <, &block> ) → other_obj

Invokes the method identified by symbol, passing it any arguments and block. You can use BasicObject#__send__ if the name send clashes with an existing method in obj.

class Klass

def hello(*args)

"Hello " + args.join(' ')

end

end

k = Klass.new

k.send :hello, "gentle", "readers" # => "Hello gentle readers"

singleton_class

  • obj.singleton_class →klass

Returns the singleton class of obj, creating one if necessary. TrueClass, FalseClass, and NilClass are their own singleton classes. Fixnum has no singleton class.

obj = "cat"

old_way = class << obj; self; end

new_way = obj.singleton_class

old_way # => #<Class:#<String:0x007fa2b1864060>>

new_way # => #<Class:#<String:0x007fa2b1864060>>

new_way == old_way # => true

singleton_methods

  • obj.singleton_methods(all=true ) → array

Returns an array of the names of singleton methods for obj. If the optional all parameter is true, the list will include methods in modules included in obj. (The parameter defaults to false in versions of Ruby prior to January 2004.)

module Other

def three(); end

end

class Single

def Single.four(); end

end

a = Single.new

def a.one(); end

class << a

include Other

def two(); end

end

Single.singleton_methods # => [:four]

a.singleton_methods(false) # => [:one, :two]

a.singleton_methods(true) # => [:one, :two, :three]

a.singleton_methods # => [:one, :two, :three]

taint

  • obj.taint →obj

Marks obj as tainted. If the $SAFE level is greater than zero, some objects will be tainted on creation. See Chapter 26, Locking Ruby in the Safe.

tainted?

  • obj.tainted? → true or false

Returns true if the object is tainted.

a = "cat"

a.tainted? # => false

a.taint # => "cat"

a.tainted? # => true

a.untaint # => "cat"

a.tainted? # => false

tap

  • obj.tap { |val| … } →obj

Invokes the block, passing obj as a parameter. Returns obj. Allows you to write code that takes part in a method chain but that does not affect the overall value of the chain.

puts "dog"

.reverse

.tap {|o| puts "Reversed: #{o}"}

.capitalize

Produces:

Reversed: god

God

to_enum

  • obj.to_enum(using=:each,<args>+ ) → enumerator
  • obj.to_enum(using=:each,<args>+ { |*args| … } → enumerator

Returns an Enumerator object that will traverse the content of obj. By default, this enumerator will invoke the each method of self, but this can be overridden by passing a different method name as the first parameter. Any additional arguments passed to to_enum will be passed to the enumerator method.

by_bytes = "∂og".to_enum(:each_byte)

by_bytes.next # => 226

by_bytes.next # => 136

by_bytes.next # => 130

by_bytes.next # => 111

by_chars = "∂og".to_enum(:each_char)

by_chars.next # => "∂"

by_chars.next # => "o"

by_chars.next # => "g"

If the block is present, it is called to return the size of the collection without actually iterating over each element. This facilitates calculating the size of lazily evaluated enumerations.«2.0»

to_s

  • obj.to_s →string

Returns a string representing obj. The default to_s prints the object’s class and an encoding of the object ID. As a special case, the top-level object that is the initial execution context of Ruby programs returns “main.”

trust

  • obj.trust →obj

Marks obj as trusted. (See the section on trust.)

untaint

  • obj.untaint →obj

Removes the taint from obj.

untrust

  • obj.untrust →obj

Marks obj as untrusted. (See the section on trust.)

untrusted?

  • obj.untrusted? → true or false

Returns true if obj is untrusted, false otherwise.

Object: Private instance methods

__callee__

  • __callee__ →symbol or nil

Returns the name of the current method or nil outside the context of a method. If a method is called by an aliased name, that alias is returned, and not the original name.«2.0»

def fred

puts "I'm in #{__callee__.inspect}"

end

fred

puts "Then in #{__callee__.inspect}"

Produces:

I'm in :fred

Then in nil

__dir__

  • __dir__ →string

The absolute path to the directory of the file containing the call to this method.«2.0»

__method__

  • __method__ →symbol or nil

Synonym for __callee__ .

‘ (backquote)

  • cmd‘ →string

Returns the standard output of running cmd in a subshell. The built-in syntax %x{...} described in the tutorial uses this method. Sets $? to the process status.

`date` # => "Mon May 27 12:32:35 CDT 2013\n"

`ls testdir`.split[1] # => "main.rb"

`echo oops && exit 99` # => "oops\n"

$?.exitstatus # => 99

Array

  • Array(arg ) → array

Returns arg as an Array. First tries to call arg.to_ary and then arg.to_a. If both fail, creates a single element array containing arg (or an empty array if arg is nil).

Array(1..5) # => [1, 2, 3, 4, 5]

Complex

  • Complex(real, imag=0 ) → complex

Returns the complex number with the given real and imaginary parts.

Complex(1) # => 1+0i

Complex("1") # => 1+0i

Complex("1", "3/2") # => 1+3/2i

Complex("3+2i") # => 3+2i

Float

  • Float(arg ) → float

Returns arg converted to a float. Numeric types are converted directly; strings are converted by interpreting their content as either a decimal or (with a loading 0x) a hexadecimal floating-point constant—see the %a field specifier to sprintf; the rest are converted using arg.to_f. Converting nil generates a TypeError.

Float(1) # => 1.0

Float("123.456") # => 123.456

Float("0x1.921fb54442d18p+1") # => 3.141592653589793

Hash

  • Hash(arg ) → hash

Convert arg to a hash by calling its to_hash method.«2.0»

Hash(nil) # => {}

Hash(x: 23, y: 67) # => {:x=>23, :y=>67}

h1 = { a:1, c:3 }

h2 = { b:2, d:4 }

Hash(**h1, **h2) # => {:a=>1, :c=>3, :b=>2, :d=>4}

Integer

  • Integer(arg ) → int

Converts arg to a Fixnum or Bignum. Numeric types are converted directly (floating-point numbers are 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. Converting nil generates a TypeError.

Integer(123.999) # => 123

Integer("0x1a") # => 26

Rational

  • Rational(numerator, denominator=1 ) → rational

Returns the rational number with the given representation.

Rational(1) # => 1/1

Rational("1") # => 1/1

Rational("1", "2") # => 1/2

Rational(1, 0.5) # => 2/1

Rational("3/2") # => 3/2

Rational("3/2", "4/5") # => 15/8

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"

abort

  • abort
  • abort(msg )

Terminates execution immediately with an exit code of 1. The optional String parameter is written to standard error before the program terminates.

at_exit

  • at_exit { … } →proc

Converts block to a Proc object 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

autoload

  • autoload(name, file_name ) → nil

Registers file_name to be loaded (using Object#require) the first time that the module name (which may be a String or a symbol) is accessed.

autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")

Module.autoload lets you define namespace-specific autoload hooks:

module X

autoload :XXX, "xxx.rb"

end

Note that xxx.rb should define a class in the correct namespace. That is, in this example, xxx.rb should contain the following:

class X::XXX

# ...

end

autoload?

  • autoload?(name ) → file_name or nil

Returns the name of the file that will be autoloaded when the string or symbol name is referenced in the top-level context or returns nil if there is no associated autoload.

autoload(:Fred, "module_fred") # => nil

autoload?(:Fred) # => "module_fred"

autoload?(:Wilma) # => nil

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 get_binding(param)

return binding

end

b = get_binding("hello")

eval("param", b) # => "hello"

block_given?

  • block_given? → true or false

Returns true if yield executes a block in the current context.

def try

if block_given?

yield

else

"no block"

end

end

try # => "no block"

try { "hello" } # => "hello"

block = lambda { "proc object" }

try(&block) # => "proc object"

caller

  • caller(<start max_size> ) → array
  • caller(<range> ) → 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. The optional max_size parameter sets the maximum size of the returned array.«2.0»Alternatively, passing a range parameter retrieves the given stack entries.

def a(skip)

caller(skip)

end

def b(skip)

a(skip)

end

def c(skip)

b(skip)

end

c(0) # => ["prog.rb:2:in `a'", "/tmp/prog.rb:5:in `b'", "/tmp/prog.rb:8:in

# .. `c'", "/tmp/prog.rb:10:in `<main>'"]

c(1) # => ["prog.rb:5:in `b'", "/tmp/prog.rb:8:in `c'", "/tmp/prog.rb:11:in

# .. `<main>'"]

c(2) # => ["prog.rb:8:in `c'", "/tmp/prog.rb:12:in `<main>'"]

c(3) # => ["prog.rb:13:in `<main>'"]

caller_locations

  • caller_locations → array of caller sites

Returns an array containing the call stack.«2.0»

def outer

inner

end

def inner

p caller_locations

end

puts outer

Produces:

["prog.rb:2:in `outer'", "/tmp/prog.rb:9:in `<main>'"]

prog.rb:2:in `outer'

prog.rb:9:in `<main>'

catch

  • catch(object=Object.new ) { … } → obj

catch executes its block. If a throw is encountered, Ruby searches up its stack for a catch block with a parameter identical to the throw ’s parameter. If found, that block is terminated, and catch returns the value given as the second parameter 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. Prior to Ruby 1.9, the parameters to catch and throw had to be symbols—they can now be any object. When using literals, it probably makes sense to use only immediate objects.

def routine(n)

print n, ' '

throw :done if n <= 0

routine(n-1)

end

catch(:done) { routine(4) }

Produces:

4 3 2 1 0

chomp

  • chomp(<rs> ) → $_ or <string>

Equivalent to $_ = $_.chomp(rs), except no assignment is made if chomp doesn’t change $_. See String#chomp. Available only if the -n or -p command-line options are present.

chop

  • chop →string

(Almost) equivalent to $_.dup.chop!, except that if chop performs no action, $_ is unchanged and nil is not returned. See String#chop!. Available only if the -n or -p command-line option is present.

define_method

  • define_method(symbol, method ) → method
  • define_method(symbol ) { … } → proc

Defines a global method.«2.0» The behavior is analogous to Module#define_method.

define_method(:adder, -> (a, b) { a+b })

adder(1, 2) # => 3

adder("cat", "dog") # => "catdog"

Note that it is possible to define methods with names that are not valid if you were to use the def keyword. These methods cannot be invoked directly.

class Silly

define_method("Oh !@!#^!") { "As Snoopy says" }

end

Silly.new.send("Oh !@!#^!") # => "As Snoopy says"

eval

  • eval(string <, binding file line>) → obj

Evaluates the Ruby expression(s) in string. If binding is given, the evaluation is performed in its context. The binding must be a Binding object. If the optional file and line parameters are present, they will be used when reporting syntax errors.

def get_binding(str)

return binding

end

str = "hello"

eval "str + ' Fred'" # => "hello Fred"

eval "str + ' Fred'", get_binding("bye") # => "bye Fred"

Local variables assigned within an eval are available after the eval only if they were defined at the outer scope before the eval executed. In this way, eval has the same scoping rules as blocks.

a = 1

eval "a = 98; b = 99"

puts a

puts b

Produces:

98

prog.rb:4:in `<main>': undefined local variable or method `b' for main:Object

(NameError)

exec

  • exec(<env,> command <, args>*, <options> )

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 command contains a newline or any of the characters ?*?{}[]<>()~&|$;’‘", or under Windows ifcommand looks like a shell-internal command (for example dir), command is run under a shell. On Unix system, Ruby does this by prepending sh -c. Under Windows, it uses the name of a shell in either RUBYSHELL or COMSPEC.

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). Raises SystemCallError if thecommand couldn’t execute (typically Errno::ENOENT).

exec "echo *" # echoes list of files in current directory

# never get here

exec "echo", "*" # echoes an asterisk

# never get here

env, if present, is a hash that adds to the environment variables in the subshell. An entry with a nil value clears the corresponding environment variable. The keys must be strings. options, if present, is a hash that controls the setup of the subshell. The possible keys and their meanings are listed under #spawn . See also Object#spawn and Object#system.

exit

  • exit( true | false |status=1 )

Initiates the termination of the Ruby script. If called in the scope of an exception handler, raises a SystemExit exception. This exception may be caught. Otherwise, exits the process using exit(2). The optional parameter is used to return a status code to the invoking environment. With an argument of true, exits with a status of zero. With an argument that is false (or no argument), exits with a status of 1; otherwise, exits with the given status. The default exit value is 1.

fork { exit 99 }

Process.wait

puts "Child exits with status: #{$?.exitstatus}"

begin

exit

puts "never get here"

rescue SystemExit

puts "rescued a SystemExit exception"

end

puts "after begin block"

Produces:

Child exits with status: 99

rescued a SystemExit exception

after begin block

Just prior to termination, Ruby executes any at_exit functions and runs any object finalizers (see ObjectSpace).

at_exit { puts "at_exit function" }

ObjectSpace.define_finalizer("xxx", lambda { |obj| puts "in finalizer" })

exit

Produces:

at_exit function

in finalizer

exit!

  • exit!( true | false |status=1 )

Similar to Object#exit, but exception handling, at_exit functions, and finalizers are bypassed.

fail

  • fail
  • fail(message )
  • fail(exception <, message array> )}

Synonym for Object#raise.

fork

  • fork<> → int or nil

Creates a subprocess. If a block is specified, that block is run in the subprocess, and the subprocess terminates with a status of zero. Otherwise, the fork call returns twice, once in the parent, returning the process ID of the child, and once in the child, returning nil. The child process can exit using Object#exit! to avoid running any at_exit functions. The parent process should use Process.wait to collect the termination statuses of its children or it should call Process.detach to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.

fork do

3.times {|i| puts "Child: #{i}" }

end

3.times {|i| puts "Parent: #{i}" }

Process.wait

Produces:

Parent: 0

Child: 0

Parent: 1

Child: 1

Parent: 2

Child: 2

format

  • format(format_string <, arg>* ) → string

Synonym for Object#sprintf.

gem

  • gem(gem_name <, version> ) → true or false

Adds the given gem to the applications include path so that subsequent requires will search. Defaults to the latest version of the gem if no version information is given. See Gems and Versions for more information and examples.

gem_original_require

  • gem_original_require<filename>+

The version of Object#require that does not know about RubyGems.

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) reads the contents one file at a time. Programming using $_ as an implicit parameter is losing favor in the Ruby community.

ARGV << "testfile"

print while gets

Produces:

This is line one

This is line two

This is line three

And so on...

global_variables

  • global_variables →array

Returns an array of the names of global variables.

global_variables.grep /std/ # => [:$stdin, :$stdout, :$stderr]

gsub

  • gsub(pattern, replacement ) → string
  • gsub(pattern ) { … } → string

Equivalent to $_.gsub(...), except that $_ will be updated if substitution occurs. Available only when the -n or -p command-line option is present.

initialize

  • initialize(< arg >+ )

Called as the third and final step in object construction, initialize is responsible for setting up the initial state of the new object. You use the initialize method the same way you’d use constructors in other languages. If you subclass classes other than Object, you will probably want to call super to invoke the parent’s initializer.

class A

def initialize(p1)

puts "Initializing A: p1 = #{p1}"

@var1 = p1

end

end

class B < A

attr_reader :var1, :var2

def initialize(p1, p2)

super(p1)

puts "Initializing B: p2 = #{p2}"

@var2 = p2

end

end

b = B.new("cat", "dog")

puts b.inspect

Produces:

Initializing A: p1 = cat

Initializing B: p2 = dog

#<B:0x007f817990eaa0 @var1="cat", @var2="dog">

iterator?

  • iterator? → true or false

Deprecated synonym for Object#block_given?.

lambda

  • lambda { … } →proc

Creates a new procedure object from the given block. See the discussion in the tutorial for an explanation of the difference between procedure objects created using lambda and those created using Proc.new. Note that lambda is now preferred over proc .

prc = lambda { "hello" }

prc.call # => "hello"

load

  • load(file_name, wrap=false ) → true

Loads and executes the Ruby program in the file file_name. 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.

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]

Note that local variables are associated with bindings.

def fred

a = 1

b = 2

binding

end

freds_binding = fred

eval("local_variables", freds_binding) # => [:a, :b]

loop

  • loop<>

Repeatedly executes the block.

loop do

print "Type something: "

line = gets

breakif line.nil? || line =~ /^[qQ]/

# ...

end

loop silently rescues the StopIteration exception, which works well with external iterators.

enum1 = [1, 2, 3].to_enum

enum2 = [10, 20].to_enum

loop do

puts enum1.next + enum2.next

end

Produces:

11

22

open

  • open(name <, mode permission> ) → io or nil
  • open(name <, mode permission> ) { |io| … } → obj

Creates an IO object connected to the given stream, file, or subprocess.

If name does not start with a pipe character (|), treats it as the name of a file to open using the specified mode defaulting to "r" (see Table 16, Mode values). If a file is being created, its initial permissions may be set using the third parameter, which is an integer. If this third parameter is present, the file will be opened using the low-level open(2) call rather than the fopen(3) call.

If a block is specified, it will be invoked with the IO object as a parameter, which will be closed when the block terminates. The call returns the value of the block in this case.

If name starts with a pipe character, a subprocess is created, connected to the caller by a pair of pipes. The returned IO object may be used to write to the standard input and read from the standard output of this subprocess. If the command following | is a single minus sign, Ruby forks, and this subprocess is connected to the parent. In the subprocess, the open call returns nil. If the command is not "--", the subprocess runs the command. If a block is associated with an open("|--") call, that block will be run twice—once in the parent and once in the child. The block parameter will be an IO object in the parent and nil in the child. The parent’s IO object will be connected to the child’s STDIN and STDOUT. The subprocess will be terminated at the end of the block.

open("testfile", "r:iso-8859-1") do |f|

print f.gets

end

Produces:

This is line one

Open a subprocess, and read its output:

cmd = open("|date")

print cmd.gets

cmd.close

Produces:

Mon May 27 12:32:39 CDT 2013

Open a subprocess running the same Ruby program:

f = open("|-", "w+")

if f.nil?

puts "in Child"

exit

else

puts "Got: #{f.gets}"

end

Produces:

Got: in Child

Open a subprocess using a block to receive the I/O object:

open("|-") do |f|

if f.nil?

puts "in Child"

else

puts "Got: #{f.gets}"

end

end

Produces:

Got: in Child

p

  • p(<obj>+ ) → obj

For each object, writes obj.inspect followed by the current output record separator to the program’s standard output. Also see the PrettyPrint library. Returns obj.

Info = Struct.new(:name, :state)

p Info['dave', 'TX']

Produces:

#<struct Info name="dave", state="TX">

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 print method.

print "cat", [1,2,3], 99, "\n"

$, = ", "

$\ = "\n"

print "cat", [1,2,3], 99

Produces:

cat[1, 2, 3]99

cat, [1, 2, 3], 99

printf

  • printf(io, format <, obj>* ) → nil
  • printf(format <, obj>* ) → nil

Equivalent to the following:

io.write(sprintf(format, obj, ...))

# or

write(sprintf(format, obj, ...))

proc

  • proc { … } →a_proc

Creates a new procedure object from the given block. Use Object#lambda instead.

prc = proc {|name| "Goodbye, #{name}" }

prc.call('Dave') # => "Goodbye, Dave"

putc

  • putc(obj ) → obj

Equivalent to STDOUT.putc(obj). If obj is a string, output its first character; otherwise, attempts to convert obj to an integer and outputs the corresponding character code.

putc 65

putc 66.123

putc "CAT"

putc 12 # newline

Produces:

ABC

puts

  • puts(<arg>* ) → nil

Equivalent to STDOUT.puts(arg...).

raise

  • raise
  • raise(message )
  • raise(exception <, message array> )

With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. With a single String argument (or an argument that responds to to_str ), 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 when its exception method is called). 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

rand

  • rand(max=0 ) → number
  • rand(range ) → number

Converts max to an integer using max1 = max.to_i.abs. If the result is zero or nil, 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. If a range is passed, return a random number in that range. Object#srand may be used to ensure repeatable sequences of random numbers between different runs of the program. See also class Random.

srand 1234 # => 272125880215485747773990619030416710243

[ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]

[ rand(10), rand(1000) ] # => [4, 664]

srand 1234 # => 1234

[ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]

rand(5..10) # => 9

rand(1.1..1.2) # => 1.1612111893665362

readline

  • readline(<separator=$/> ) → string

Equivalent to Object#gets, except readline raises EOFError at end of file.

readlines

  • readlines(<separator=$/> ) → array

Returns an array containing each of the lines returned by calling gets(separator).

remove_instance_variable

  • remove_instance_variable(symbol ) → other_obj

Removes the named instance variable from obj, returning that variable’s value.

class Dummy

def initialize

@var = 99

end

def remove

remove_instance_variable(:@var)

end

def var_defined?

defined? @var

end

end

d = Dummy.new

d.var_defined? # => "instance-variable"

d.remove # => 99

d.var_defined? # => nil

require

  • require(library_name ) → true or false

Ruby tries to load library_name, returning true if successful. If the filename is not 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,[119] 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 its name already appears in $".[120] require returns true if the feature was successfully loaded.

require 'my-library.rb'

require 'db-driver'

require_relative

  • require_relative(library_path ) → true or false

Requires a library whose path is relative to the file containing the call. Thus, if the directory /usr/local/mylib/bin contains the file myprog.rb and that program contains the following line:

require_relative "../lib/mylib"

then Ruby will look for mylib in /usr/local/mylib/lib.

require_relative cannot be called interactively in irb.

select

  • select(read_array <, write_array error_array timeout> ) → array or nil

Performs a low-level select call, which waits for data to become available from input/output devices. The first three parameters are arrays of IO objects or nil. The last is a timeout in seconds, which should be an Integer or a Float. The call waits for data to become available for any of the IO objects in read_array, for buffers to have cleared sufficiently to enable writing to any of the devices in write_array, or for an error to occur on the devices in error_array. If one or more of these conditions are met, the call returns a three-element array containing arrays of the IO objects that were ready. Otherwise, if there is no change in status for timeout seconds, the call returns nil. If all parameters are nil, the current thread sleeps forever.

select( [STDIN], nil, nil, 1.5 ) # => nil

set_trace_func

  • set_trace_func(proc ) → proc
  • set_trace_func( nil ) → nil

(This method has been replaced by the TracePoint class in Ruby 2.0.)«2.0» 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 call (calls a Ruby method), c-call (calls a C-language routine), c-return (returns from a C-language routine), class (starts a class or module definition), end (finishes a class or module definition), line (executes code on a new line), raise (raises an exception), and return (returns from a Ruby method). Tracing is disabled within the context of proc. See the example in the tutorial for more information.

sleep

  • sleep(numeric=0 ) → fixnum

Suspends the current thread for numeric seconds (which may be a Float with fractional seconds). Returns the actual number of seconds slept (rounded), which may be less than that asked for if the thread was interrupted by a SIGALRM or if another thread calls Thread#run. An argument of zero causes sleep to return immediately.

Time.now # => 2013-05-27 12:32:41 -0500

sleep 1.9 # => 2

Time.now # => 2013-05-27 12:32:43 -0500

spawn

  • spawn(<env,> command <, args>*, <options> ) → pid

Executes command in a subshell, returning immediately. (Compare with Object#system, which waits for the command to complete before returning to the caller.) Returns the process ID for the subprocess running the command.

The command can be a string, which is passed to the system shell for interpretation or a command name followed by zero or more arguments. In this case, the command is executed and passed the given arguments—the shell is not involved. The command name may be a string or a two-element array, where the first element is the command itself and the second is the argv[0] value to be passed to exec(2). The latter may be used to change the process name on systems that support it.

pid = spawn("echo hello")

puts "Back in main program"

STDOUT.flush

rc, status = Process::waitpid2(pid)

puts "Status = #{status}"

Produces:

Back in main program

hello

Status = pid 23941 exit 0

env, if present, is a hash that adds to the environment variables in the subshell. An entry with a nil value clears the corresponding environment variable. The keys must be strings.

pid = spawn({"FRED" => "caveman"}, "echo FRED = $FRED")

Process::waitpid2(pid)

Produces:

FRED = caveman

The options hash controls the setup of the subshell. Keys and their meanings are:

Option

Effect on new process

:pgroup => true | 0 | int

If true or 0, the new process will be a process group leader. Otherwise, the process will belong to group int.

:rlimit_xxx => val | [cur, max]

Sets a resource limit. See Process.getrlimit for more information.

:unsetenv_others => true

Clears all environment variables; then sets only those passed in the env parameter.

:chdir => dir

Changes to directory dir before running the process.

:umask => int

Specifies the umask for the process.

fd_desc => stream

Sets the process’s standard input, output, or error to stream. See the description that follows this table for information.

:close_others => true | false

By default, all file descriptors apart from 0, 1, and 2 are closed. You can specify false to leave them open.

io_obj => :close

Explicitly closes the file descriptor corresponding to io_obj in the child process.

The fd_desc parameter identifies an I/O stream to be opened or assigned in the child process. It can be one of :in, STDIN, or 0 to represent standard input; :out, STDOUT, or 1 for standard output; or :err, STDERR, or 2 for standard error. It can also be an array containing one or more of these, in which case all fds in the array will be opened on the same stream.

The stream parameter can be the following:

  • One of :in, STDIN, or 0 to represent the current standard input; :out, STDOUT, or 1 for the current standard output; or :err, STDERR, or 2 for the current standard error.
  • A string representing the name of a file or device.
  • An array. If it contains [:child, fd], redirects to the fd of the child process. Otherwise, the first element is the name of a file or device, the optional second element is the mode, and the optional third element the permission. See the description ofFile#new for details.

This example shows the options in action:

reader, writer = IO.pipe

pid = spawn("echo '4*a(1)' | bc -l", [ STDERR, STDOUT ] => writer)

writer.close

Process::waitpid2(pid)

reader.gets # => "3.14159265358979323844\n"

sprintf

  • 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; an optional name; and then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, and the flags modify that interpretation.

The flag characters are:

Flag

Applies To

Meaning

␣ (space)

bdEefGgiouXx

Leaves 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

Uses an alternative format. For the conversions b, o, X, and x, prefixes the result with b, 0, 0X, 0x, respectively. For E, e, f, G, and g, forces a decimal point to be added, even if no digits follow. For G and g, does not remove trailing zeros.

+

bdEefGgiouXx

Adds a leading plus sign to positive numbers.

-

all

Left-justifies the result of this conversion.

0 (zero)

bdEefGgiouXx

Pads with zeros, not spaces.

*

all

Uses the next argument as the field width. If negative, left-justifies the result. If the asterisk is followed by a number and a dollar sign, uses 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. As of Ruby 1.9, the number zero is converted to a zero-length string if a precision of 0 is given. 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 type characters are:

Field

Conversion

A

Same as %a, but uses uppercase X and P.

a

Converts a float into hexadecimal representation 0xsignificandpdecimal-exp.

B

Converts argument as a binary number (0B0101 if # modifier used).

b

Converts argument as a binary number (0b0101 if # modifier used).

c

Argument is the numeric code for a single character.

d

Converts argument as a decimal number.

E

Equivalent to e but uses an uppercase E to indicate the exponent.

e

Converts floating point-argument into exponential notation with one digit before the decimal point. The precision determines the number of fractional digits (default six).

f

Converts floating-point argument as [␣|-]ddd.ddd, where the precision determines the number of digits after the decimal point.

G

Equivalent to g but uses an uppercase E in exponent form.

g

Converts 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

Converts argument as an octal number.

p

The value 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

Treats argument as an unsigned decimal number.

X

Converts argument to hexadecimal with uppercase letters. Negative numbers will be displayed with two leading periods (representing an infinite string of leading FFs).

x

Converts argument to hexadecimal. Negative numbers will be displayed with two leading periods (representing an infinite string of leading FFs).

Here are some examples of sprintf in action:

sprintf("%d %04x", 123, 123) # => "123007b"

sprintf("%08b '%4s'", 123, 123) # => "01111011'123'"

sprintf("%1$*2$s %2$d %1$s", "hello", 8) # => "␣␣␣hello8hello"

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"

In Ruby 1.9, you can pass a hash as the second argument and insert values from this hash into the string. The notation <name> can be used between a percent sign and a field-type character, in which case the name will be used to look up a value in the hash, and that value will be formatted according to the field specification. The notation {name} is equivalent to <name>s, substituting the corresponding value as a string. You can use width and other flag characters between the opening percent sign and the {.

sprintf("%<number>d %04<number>x", number: 123) # => "123007b"

sprintf("%08<number>b '%5{number}'", number: 123) # => "01111011'␣␣123'"

sprintf("%6<k>s: %<v>s", k: "Dave", v: "Ruby") # => "␣␣Dave:Ruby"

sprintf("%6{k}: %{v}", k: "Dave", v: "Ruby") # => "␣␣Dave:Ruby"

srand

  • srand(<number> ) → old_seed

Seeds the pseudorandom number generator to the value of number. to_i . If number is omitted or zero, uses Random.new_seed. (This is also the behavior if Object#rand is called without previously calling srand but without the sequence.) By setting the seed to a known value, scripts that use rand can be made deterministic during testing. The previous seed value is returned. Also see Object#rand and class Random.

sub

  • sub(pattern, replacement ) → $_
  • sub(pattern ) { block } → $_

Equivalent to $_.sub(args), except that $_ will be updated if substitution occurs. Available only if the -n or -p command-line option is present.

syscall

  • syscall(fixnum <, args>* ) → int

Calls the operating system function identified by fixnum. The arguments must be either String objects or Integer objects that fit within a native long. Up to nine parameters may be passed. The function identified by fixnum is system dependent. On some Unix systems, the numbers may be obtained from a header file called syscall.h. System is not always available.

syscall 4, 1, "hello\n", 6 # '4' is write(2) on our system

system

  • system(<env,> command <, args>*, <options> ) → true or false~or nil

Executes command in a subshell, returning true if the command was found and ran successfully, false if the command exited with a nonzero exit status, and nil if the command failed to execute. An error status is available in $?. The arguments are processed in the same way as for Object#exec.env, if present, is a hash that adds to the environment variables in the subshell. An entry with a nil value clears the corresponding environment variable. The keys must be strings. options, if present, is a hash that controls the setup of the subshell. The possible keys and their meanings are listed under the spawn method.

system("echo *")

system("echo", "*")

system({"WILMA" => "shopper"}, "echo $WILMA")

Produces:

config.h main.rb

*

shopper

test

  • test(cmd,file1 <, file2> ) → obj

Uses cmd to perform various tests on file1 (see the first table that follows) or on file1 and file2 (see the second table).

Flag

Description

Returns

?A

Last access time for file1

Time

?b

True if file1 is a block device

true or false

?c

True if file1 is a character device

true or false

?C

Last change time for file1

Time

?d

True if file1 exists and is a directory

true or false

?e

True if file1 exists

true or false

?f

True if file1 exists and is a regular file

true or false

?g

True if file1 has the setgid bit set (false under NT)

true or false

?G

True if file1 exists and has a group ownership equal to the caller’s group

true or false

?k

True if file1 exists and has the sticky bit set

true or false

?l

True if file1 exists and is a symbolic link

true or false

?M

Last modification time for file1

Time

?o

True if file1 exists and is owned by the caller’s effective UID

true or false

?O

True if file1 exists and is owned by the caller’s real UID

true or false

?p

True if file1 exists and is a fifo

true or false

?r

True if file1 is readable by the effective UID/GID of the caller

true or false

?R

True if file1 is readable by the real UID/GID of the caller

true or false

?s

If file1 has nonzero size, returns the size; otherwise, returns nil

Integer or nil

?S

True if file1 exists and is a socket

true or false

?u

True if file1 has the setuid bit set

true or false

?w

True if file1 exists and is writable by the effective UID/ GID

true or false

?W

True if file1 exists and is writable by the real UID/GID

true or false

?x

True if file1 exists and is executable by the effective UID/GID

true or false

?X

True if file1 exists and is executable by the real UID/GID

true or false

?z

True if file1 exists and has a zero length

true or false

Flag

Description

?-

True if file1 is a hard link to file2

?=

True if the modification times of file1 and file2 are equal

?<

True if the modification time of file1 is prior to that of file2

?>

True if the modification time of file1 is after that of file2

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 Object#catch.

trace_var

  • trace_var(symbol, cmd ) → nil
  • trace_var(symbol ) { |val| … } → 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 the block is executed whenever the variable is assigned and receives the variable’s new value as a parameter. Only explicit assignments are traced. Also see Object#untrace_var.

trace_var :$dave, lambda {|v| puts "$dave is now '#{v}'" }

$dave = "hello"

$dave.sub!(/ello/, "i")

$dave += " Dave"

Produces:

$dave is now 'hello'

$dave is now 'hi Dave'

trap

  • trap(signal, proc ) → obj
  • trap(signal ) { … } → obj

See the Signal module.

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.

using

  • usingmod

Applies the refinements defined in the given module. The refinements apply to the current file (or string if eval is being used) from the point where using is called.«2.0»

module SuperUpcase

refine String do

def upcase

"!WOW! #{super} !WOW!"

end

end

end

"wombat".upcase # => "WOMBAT"

using SuperUpcase

"wombat".upcase # => "!WOW! WOMBAT !WOW!"

warn

  • warn<msgs>+

Writes the given message to STDERR (unless $VERBOSE is nil, perhaps because the -W0 command-line option was given). If multiple messages are given, writes each on a new line.«2.0»

warn "Danger, Will Robinson!"

Produces:

Danger, Will Robinson!

Module ObjectSpace

The ObjectSpace module contains a number of routines that interact with the garbage collection facility and allow you to traverse all living objects with an iterator.

ObjectSpace also provides support for object finalizers. These are procs that will be called when a specific object is about to be destroyed by garbage collection.

include ObjectSpace

a, b, c = "A", "B", "C"

puts "a's id is #{a.object_id}"

puts "b's id is #{b.object_id}"

puts "c's id is #{c.object_id}"

define_finalizer(a, lambda {|id| puts "Finalizer one on #{id}" })

define_finalizer(b, lambda {|id| puts "Finalizer two on #{id}" })

define_finalizer(c, lambda {|id| puts "Finalizer three on #{id}" })

Produces:

a's id is 70124883293000

b's id is 70124883292960

c's id is 70124883292880

Finalizer three on 70124883292880

Finalizer two on 70124883292960

Finalizer one on 70124883293000

ObjectSpace: Module methods

_id2ref

  • ObjectSpace._id2ref(object_id ) → obj

Converts an object ID to a reference to the object. May not be called on an object ID passed as a parameter to a finalizer.

s = "I am a string" # => "I am a string"

oid = s.object_id # => 70207029149080

r = ObjectSpace._id2ref(oid) # => "I am a string"

r # => "I am a string"

r.equal?(s) # => true

count_objects

  • ObjectSpace.count_objects →histogram_hash

Returns a hash where the keys are the interpreter-specific internal object types and the values are the number of objects of each type.

ObjectSpace.count_objects # => {:TOTAL=>17493, :FREE=>60, :T_OBJECT=>49,

# .. :T_CLASS=>471, :T_MODULE=>21, :T_FLOAT=>4,

# .. :T_STRING=>7748, :T_REGEXP=>64, :T_ARRAY=>1464,

# .. :T_HASH=>57, :T_BIGNUM=>3, :T_FILE=>17,

# .. :T_DATA=>701, :T_MATCH=>20, :T_COMPLEX=>1,

# .. :T_RATIONAL=>2, :T_NODE=>6790, :T_ICLASS=>21}

define_finalizer

  • ObjectSpace.define_finalizer(obj, a_proc=proc() )

Adds a_proc as a finalizer, called when obj is about to be destroyed. Note that if you use lambda to create the proc object, you must remember to include a parameter with the block. If you don’t, the invocation of the lambda will silently fail when the finalizer is called because of a mismatch in the expected and actual parameter count.

each_object

  • ObjectSpace.each_object(< class_or_mod> ) { |obj| … } → fixnum

Calls the block once for each living, nonimmediate object in this Ruby process. If class_or_mod is specified, calls the block for only those classes or modules that match (or are a subclass of) class_or_mod. Returns the number of objects found. Immediate objects (Fixnums, Symbols true, false, and nil) are never returned. In the following example, each_object returns both the numbers we defined and several constants defined in the Math module:

a = 102.7

b = 95 # Fixnum: won't be returned

c = 12345678987654321

count = ObjectSpace.each_object(Numeric) {|x| p x }

puts "Total count: #{count}"

Produces:

(0+1i)

9223372036854775807

3

NaN

Infinity

1.7976931348623157e+308

2.2250738585072014e-308

274193223623034780067407936393989039126

12345678987654321

Total count: 9

garbage_collect

  • ObjectSpace.garbage_collect → nil

Initiates garbage collection (see module GC).

undefine_finalizer

  • ObjectSpace.undefine_finalizer(obj )

Removes all finalizers for obj.

Class Proc < Object

Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.

def gen_times(factor)

return Proc.new {|n| n*factor }

end

times3 = gen_times(3)

times5 = gen_times(5)

times3.call(12) # => 36

times5.call(5) # => 25

times3.call(times5.call(4)) # => 60

Proc: Class methods

new

  • Proc.new { … } →a_proc
  • Proc.new →a_proc

Creates a new Proc object, bound to the current context. Proc.new may be called without a block only within a method with an attached block, in which case that block is converted to the Proc object.

def proc_from

Proc.new

end

proc = proc_from { "hello" }

proc.call # => "hello"

Proc: Instance methods

[ ]

  • prc[<params>* ] → obj

Synonym for Proc#call.

==

Removed in Ruby 2.0«2.0».

===

  • prc=== otherobj

Equivalent to prc.call(other). Allows you to use procs in when clauses of case expressions, so you can write stuff such as:

even = lambda {|num| num.even? }

(0..3).each do |num|

case num

when even then puts "#{num} is even"

else puts "#{num} is not even"

end

end

Produces:

0 is even

1 is not even

2 is even

3 is not even

arity

  • prc.arity →integer

Returns the number of arguments required by the block. If the block is declared to take no arguments, returns 0. If the block is known to take exactly n arguments, returns n. If the block has optional arguments, returns -(n+1), where n is the number of mandatory arguments. A proc with no argument declarations also returns -1, because it can accept (and ignore) an arbitrary number of parameters.

Proc.new {}.arity # => 0

Proc.new {||}.arity # => 0

Proc.new {|a|}.arity # => 1

Proc.new {|a,b|}.arity # => 2

Proc.new {|a,b,c|}.arity # => 3

Proc.new {|*a|}.arity # => -1

Proc.new {|a,*b|}.arity # => -2

In Ruby 1.9, arity is defined as the number of parameters that would not be ignored. In 1.8, Proc.new {}.arity returns -1, and in 1.9 it returns 0.

binding

  • prc.binding →binding

Returns the binding associated with prc.

def some_method

a = "wibble"

lambda {}

end

prc = some_method

eval "a", prc.binding # => "wibble"

call

  • prc.call(<params>* ) → obj

Invokes the block, setting the block’s parameters to the values in params using something close to method-calling semantics. Returns the value of the last expression evaluated in the block.

a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}

a_proc.call(9, 1, 2, 3) # => [9, 18, 27]

a_proc[9, 1, 2, 3] # => [9, 18, 27]

If the block being called accepts a single parameter and you give call more than one parameter, only the first will be passed to the block. This is a change from Ruby 1.8.

a_proc = Proc.new {|a| puts a}

a_proc.call(1,2,3)

Produces:

1

If you want a block to receive an arbitrary number of arguments, define it to accept *args.

a_proc = Proc.new {|*a| p a}

a_proc.call(1,2,3)

Produces:

[1, 2, 3]

Blocks created using Object#lambda check that they are called with exactly the right number of parameters.

p_proc = Proc.new {|a,b| puts "Sum is: #{a + b}" }

p_proc.call(1,2,3)

p_proc = lambda {|a,b| puts "Sum is: #{a + b}" }

p_proc.call(1,2,3)

Produces:

from prog.rb:4:in `call'

from prog.rb:4:in `<main>'

Sum is: 3

prog.rb:3:in `block in <main>': wrong number of arguments (3 for 2)

(ArgumentError)

curry

  • prc.curry →curried_proc

If you have a proc that takes arguments, you normally have to supply all of those arguments if you want the proc to execute successfully. However, it is also possible to consider an n argument proc to be the same as a single-argument proc that returns a new proc that has this first argument fixed and that takes n-1 arguments. If you repeat this process recursively for each of these subprocs, you end up with a proc that will take from zero to n arguments. If you pass it all n, it simply executes the proc with those arguments. If you pass it m arguments (where m < n), it returns a new proc that has those arguments prebaked in and that takes m-n arguments. In this way, it is possible to partially apply arguments to a proc.

add_three_numbers = lambda {|a,b,c| a + b + c}

add_10_to_two_numbers = add_three_numbers.curry[10]

add_33_to_one_number = add_10_to_two_numbers[23]

add_three_numbers[1,2,3] # => 6

add_10_to_two_numbers[1,2] # => 13

add_33_to_one_number[1] # => 34

lambda?

  • prc.lambda? → true or false

Returns true if prc has lambda semantics (that is, if argument passing acts as it does with method calls). See the discussion in Section 22.13, Blocks, Closures, and Proc Objects.

parameters

  • prc.parameters →array

Returns a description of the method’s parameter list. See Method#parameters for details.

lambda {|a, b=1, *c, &d| }.parameters # => [[:req, :a], [:opt, :b], [:rest, :c],

# .. [:block, :d]]

source_location

  • prc.source_location → [filename, lineno ] or nil

Returns the source filename and line number where prc was defined or nil if proc was not defined in Ruby source.

variable = 123

prc = lambda { "some proc" }

prc.source_location # => ["prog.rb", 2]

to_proc

  • prc.to_proc →prc

Part of the protocol for converting objects to Proc objects. Instances of class Proc simply return themselves.

to_s

  • prc.to_s →string

Returns a description of prc, including information on where it was defined.

def create_proc

Proc.new

end

my_proc = create_proc { "hello" }

my_proc.to_s # => "#<Proc:0x007fc7f4864318@prog.rb:5>"

yield

  • prc.yield(<params>* ) → obj

Synonym for Proc#call.

Module Process

The Process module is a collection of methods used to manipulate processes. Programs that want to manipulate real and effective user and group IDs should also look at the Process::GID and Process::UID modules. Much of the functionality here is duplicated in the Process::Sys module.

Constants

PRIO_PGRP

Process group priority.

PRIO_PROCESS

Process priority.

PRIO_USER

User priority.

WNOHANG

Does not block if no child has exited. Not available on all platforms.

WUNTRACED

Returns stopped children as well. Not available on all platforms.

RLIM[IT]_xxx

Used by getrlimit and setrlimit .

Process: Module methods

abort

  • abort
  • abort(msg )

Synonym for Object#abort.

daemon

  • Process.daemon(stay_in_dir = false, keep_stdio_open = false ) → 0 or -1

Puts the current process into the background (either by forking and calling Process.setsid or by using the daemon(3) call if available). Sets the current working directory to / unless stay_in_dir is true. Redirects standard input, output, and error to /dev/null unless keep_stdio_open is true. Not available on all platforms.

detach

  • Process.detach(pid ) → thread

Some operating systems retain the status of terminated child processes until the parent collects that status (normally using some variant of wait() ). If the parent never collects this status, the child stays around as a zombie process. Process.detach prevents this by setting up a separate Ruby thread whose sole job is to reap the status of the process pid when it terminates. Use detach only when you do not intend to explicitly wait for the child to terminate. detach checks the status only periodically (currently once each second).

In this first example, we don’t reap the first child process, so it appears as a zombie in the process status display.

pid = fork { sleep 0.1 }

sleep 1

system("ps -o pid,state -p #{pid}")

Produces:

dyld: DYLD_ environment variables being ignored because main executable (/bin/ps)

is setuid or setgid

PID STAT

24002 Z+

In the next example, Process.detach is used to reap the child automatically—no child processes are left running.

pid = fork { sleep 0.1 }

Process.detach(pid)

sleep 1

system("ps -o pid,state -p #{pid}")

Produces:

dyld: DYLD_ environment variables being ignored because main executable (/bin/ps)

is setuid or setgid

PID STAT

egid

  • Process.egid →int

Returns the effective group ID for this process.

Process.egid # => 20

egid=

  • Process.egid=intint

Sets the effective group ID for this process.

euid

  • Process.euid →int

Returns the effective user ID for this process.

Process.euid # => 501

euid=

  • Process.euid=int

Sets the effective user ID for this process. Not available on all platforms.

exec

  • Process.exec(<env,> command <, args>*, <options> )

Synonym for Object#exec.

exit

  • Process.exit(int=0 )

Synonym for Object#exit.

exit!

  • Process.exit!( true | false |status=1 )

Synonym for Object#exit!. No exit handlers are run. 0, 1, or status is returned to the underlying system as the exit status.

Process.exit!(0)

fork

  • Process.fork<> → int or nil

See Object#fork.

getpgid

  • Process.getpgid(int ) → int

Returns the process group ID for the given process ID. Not available on all platforms.

Process.getpgid(Process.ppid()) # => 21366

getpgrp

  • Process.getpgrp →int

Returns the process group ID for this process. Not available on all platforms.

Process.getpgid(0) # => 21366

Process.getpgrp # => 21366

getpriority

  • Process.getpriority(kind, int ) → int

Gets the scheduling priority for specified process, process group, or user. The kind parameter indicates the kind of entity to find: Process::PRIO_PGRP, Process::PRIO_USER, or Process::PRIO_PROCESS. int is an ID indicating the particular process, process group, or user (an ID of 0 means current). Lower priorities are more favorable for scheduling. Not available on all platforms.

Process.getpriority(Process::PRIO_USER, 0) # => 0

Process.getpriority(Process::PRIO_PROCESS, 0) # => 0

getrlimit

  • Process.getrlimit(name ) → [ current, max ]

Returns the current and maximum resource limit for the named resource. The name may be a symbol or a string from the following list. It may also be an operating-specific integer constant. The Process module defines constants corresponding to these integers: the constants are named RLIMIT_ followed by one of the following: AS, CORE, CPU, DATA, FSIZE, MEMLOCK, NOFILE, NPROC, RSS, or STACK. Consult your system’s getrlimit(2) man page for details. The return array may contain actual values or one of the constants RLIM_INFINITY, RLIM_SAVED_CUR, or RLIM_SAVED_MAX. Not available on all platforms. See also Process.setrlimit.

Process.getrlimit(:STACK) # => [8388608, 67104768]

Process.getrlimit("STACK") # => [8388608, 67104768]

Process.getrlimit(Process::RLIMIT_STACK) # => [8388608, 67104768]

getsid

  • Process.getsid →int

Returns the session id (if supported).«2.0»

gid

  • Process.gid →int

Returns the group ID for this process.

Process.gid # => 20

gid=

  • Process.gid=intint

Sets the group ID for this process.

groups

  • Process.groups →groups

Returns an array of integer supplementary group IDs. Not available on all platforms. See also Process.maxgroups.

Process.groups # => [20, 405, 402, 401, 403, 12, 33, 61, 79, 80, 81, 98, 100,

# .. 204, 404]

groups=

  • Process.groups =arraygroups

Sets the supplementary group IDs from the given array, which may contain either numbers or group names (as strings). Not available on all platforms. Available only to superusers. See also Process.maxgroups.

initgroups

  • Process.initgroups(user, base_group ) → groups

Initializes the group access list using the operating system’s initgroups call. Not available on all platforms. May require superuser privilege.

Process.initgroups("dave", 500)

kill

  • Process.kill(signal, <pid>+ ) → int

Sends the given signal to the specified process ID(s) or to the current process if pid is zero. signal may be an integer signal number or a string or symbol representing a POSIX signal name (either with or without a SIG prefix). If signal is negative (or starts with a - sign), kills process groups instead of processes. Not all signals are available on all platforms.

pid = fork do

Signal.trap(:USR1) { puts "Ouch!"; exit }

# ... do some work ...

end

# ...

Process.kill(:USR1, pid)

Process.wait

Produces:

Ouch!

maxgroups

  • Process.maxgroups →count

The Process module has a limit on the number of supplementary groups it supports in the calls Process.groups and Process.groups=. The maxgroups call returns that limit, and the maxgroups= call sets it.

Process.maxgroups # => 16

maxgroups=

  • Process.maxgroups=limitcount

Sets the maximum number of supplementary group IDs that can be processed by the groups and groups= methods. If a number larger than 4096 is given, 4096 will be used.

pid

  • Process.pid →int

Returns the process ID of this process. Not available on all platforms.

Process.pid # => 24032

ppid

  • Process.ppid →int

Returns the process ID of the parent of this process. Always returns 0 on Windows. Not available on all platforms.

puts "I am #{Process.pid}"

Process.fork { puts "Parent is #{Process.ppid}" }

Produces:

I am 24034

Parent is 24034

setpgid

  • Process.setpgid(pid, int ) → 0

Sets the process group ID of pid (0 indicates this process) to int. Not available on all platforms.

setpgrp

  • Process.setpgrp → 0

Equivalent to setpgid(0,0). Not available on all platforms.

setpriority

  • Process.setpriority(kind, int, int_priority ) → 0

See Process#getpriority.

Process.setpriority(Process::PRIO_USER, 0, 19) # => 0

Process.setpriority(Process::PRIO_PROCESS, 0, 19) # => 0

Process.getpriority(Process::PRIO_USER, 0) # => 19

Process.getpriority(Process::PRIO_PROCESS, 0) # => 19

setrlimit

  • Process.setrlimit(name, soft_limit, hard_limit=soft_limit ) → nil

Sets the limit for the named resource. See Process.getrlimit for a description of resource naming. Your system’s setrlimit(2) man page will have a description of the limits. Not available on all platforms.

setsid

  • Process.setsid →int

Establishes this process as a new session and process group leader, with no controlling tty. Returns the session ID. Not available on all platforms.

Process.setsid # => 24039

spawn

  • Process.spawn(<env,> command <, args>*, <options> ) → pid

Synonym for Object#spawn.

times

  • Process.times →struct_tms

Returns a Tms structure (see Struct::Tms) that contains user and system CPU times for this process.

t = Process.times

[ t.utime, t.stime ] # => [0.03, 0.01]

uid

  • Process.uid →int

Returns the user ID of this process.

Process.uid # => 501

uid=

  • Process.uid=intnumeric

Sets the (integer) user ID for this process. Not available on all platforms.

wait

  • Process.wait →int

Waits for any child process to exit and returns the process ID of that child. Also sets $? to the Process::Status object containing information on that process. Raises a SystemError if there are no child processes. Not available on all platforms.

Process.fork { exit 99 } # => 24046

Process.wait # => 24046

$?.exitstatus # => 99

waitall

  • Process.waitall → [ [pid1,status ], ... ]

Waits for all children, returning an array of pid/status pairs (where status is an object of class Process::Status).

fork { sleep 0.2; exit 2 } # => 24049

fork { sleep 0.1; exit 1 } # => 24050

fork { exit 0 } # => 24051

Process.waitall # => [[24051, #<Process::Status: pid 24051 exit 0>],

# .. [24050, #<Process::Status: pid 24050 exit 1>],

# .. [24049, #<Process::Status: pid 24049 exit 2>]]

wait2

  • Process.wait2 → [pid, status ]

Waits for any child process to exit and returns an array containing the process ID and the exit status (a Process::Status object) of that child. Raises a SystemError if no child processes exist.

Process.fork { exit 99 } # => 24054

pid, status = Process.wait2

pid # => 24054

status.exitstatus # => 99

waitpid

  • Process.waitpid(pid, int=0 ) → pid

Waits for a child process to exit depending on the value of pid:

< -1

Any child whose progress group ID equals the absolute value of pid

-1

Any child (equivalent to wait )

0

Any child whose process group ID equals that of the current process

> 0

The child with the given PID

int may be a logical or of the flag values Process::WNOHANG (do not block if no child available) or Process::WUNTRACED (return stopped children that haven’t been reported). Not all flags are available on all platforms, but a flag value of zero will work on all platforms.

include Process

pid = fork { sleep 2 } # => 24057

Time.now # => 2013-05-27 12:32:49 -0500

waitpid(pid, Process::WNOHANG) # => nil

Time.now # => 2013-05-27 12:32:49 -0500

waitpid(pid, 0) # => 24057

Time.now # => 2013-05-27 12:32:51 -0500

waitpid2

  • Process.waitpid2(pid, int=0 ) → [ pid, status ]

Waits for the given child process to exit, returning that child’s process ID and exit status (a Process::Status object). int may be a logical or of the values Process::WNOHANG (do not block if no child available) or Process::WUNTRACED (return stopped children that haven’t been reported). Not all flags are available on all platforms, but a flag value of zero will work on all platforms.

Module Process::GID

Provides a higher-level (and more portable) interface to the underlying operating system’s concepts of real, effective, and saved group IDs. Discussing the semantics of these IDs is well beyond the scope of this book; readers who want to know more should consult POSIX documentation or read the intro(2) man pages on a recent Unix platform. All these methods throw NotImplementedError if the host operating does not support a sufficient set of calls. The descriptions that follow are based on notes in ruby-talk:76218 by Hidetoshi Nagai.

Process::GID: Module methods

change_privilege

  • Process::GID.change_privilege(gid ) → gid

Sets the real, effective, and saved group IDs to gid, raising an exception on failure (in which case the state of the IDs is not known). This method is not compatible with Process.gid=.

eid

  • Process::GID.eid →egid

Returns the effective group ID for this process. Synonym for Process.egid.

eid=

  • Process::GID.eid =egid

Synonym for Process::GID.grant_privilege.

grant_privilege

  • Process::GID.grant_privilege(egid ) → egid

Sets the effective group ID to egid, raising an exception on failure. On some environments this may also change the saved group ID (see re_exchangeable? ).

re_exchange

  • Process::GID.re_exchange →egid

Exchanges the real and effective group IDs, setting the saved group ID to the new effective group ID. Returns the new effective group ID.

re_exchangeable?

  • Process::GID.re_exchangeable → true or false

Returns true if real and effective group IDs can be exchanged on the host operating system and returns false otherwise.

rid

  • Process::GID.rid →gid

Returns the real group ID for this process. Synonym for Process.gid.

sid_available?

  • Process::GID.sid_available? → true or false

Returns true if the underlying platform supports saved group IDs and returns false otherwise. Currently, Ruby assumes support if the operating system has setresgid(2) or setegid(2) calls or if the configuration includes the POSIX_SAVED_IDS flag.

switch

  • Process::GID.switch →egid
  • Process::GID.switch { … } →obj

Handles the toggling of group privilege. In the block form, automatically toggles the IDs back when the block terminates (but only if the block doesn’t use other calls into Process::GID calls, which would interfere). Without a block, returns the original effective group ID.

Class Process::Status < Object

Process::Status encapsulates the information on the status of a running or terminated system process. The built-in variable $? is either nil or a Process::Status object.

fork { exit 99 } # => 24060

Process.wait # => 24060

$?.class # => Process::Status

$?.to_i # => 25344

$? >> 8 # => 99

$?.stopped? # => false

$?.exited? # => true

$?.exitstatus # => 99

POSIX systems record information on processes using a 16-bit integer. The lower bits record the process status (stopped, exited, signaled), and the upper bits possibly contain additional information (for example, the program’s return code in the case of exited processes). Before Ruby 1.8, these bits were exposed directly to the Ruby program. Ruby now encapsulates these in a Process::Status object. To maximize compatibility, however, these objects retain a bit-oriented interface. In the descriptions that follow, when we talk about the integer value of stat, we’re referring to this 16-bit value.

Process::Status: Instance methods

==

  • stat== othertrue or false

Returns true if the integer value of stat equals other.

&

  • stat& numfixnum

Logical AND of the bits in stat with num.

fork { exit 0x37 }

Process.wait

sprintf('%04x', $?.to_i) # => "3700"

sprintf('%04x', $? & 0x1e00) # => "1600"

>>

  • stat>> numfixnum

Shifts the bits in stat right num places.

fork { exit 99 } # => 24066

Process.wait # => 24066

$?.to_i # => 25344

$? >> 8 # => 99

coredump?

  • stat.coredump → true or false

Returns true if stat generated a core dump when it terminated. Not available on all platforms.

exited?

  • stat.exited? → true or false

Returns true if stat exited normally (for example using an exit call or finishing the program).

exitstatus

  • stat.exitstatus →fixnum or nil

Returns the least significant 8 bits of the return code of stat. Available only if exited? is true.

fork { } # => 24069

Process.wait # => 24069

$?.exited? # => true

$?.exitstatus # => 0

fork { exit 99 } # => 24070

Process.wait # => 24070

$?.exited? # => true

$?.exitstatus # => 99

pid

  • stat.pid →fixnum

Returns the ID of the process associated with this status object.

fork { exit } # => 24073

Process.wait # => 24073

$?.pid # => 24073

signaled?

  • stat.signaled? → true or false

Returns true if stat terminated because of an uncaught signal.

pid = fork { sleep 100 }

Process.kill(9, pid) # => 1

Process.wait # => 24076

$?.signaled? # => true

stopped?

  • stat.stopped? → true or false

Returns true if this process is stopped. This is returned only if the corresponding wait call had the WUNTRACED flag set.

success?

  • stat.success? → nil, or true or false

Returns true if stat refers to a process that exited successfully, returns false if it exited with a failure, and returns nil if stat does not refer to a process that has exited.

stopsig

  • stat.stopsig →fixnum or nil

Returns the number of the signal that caused stat to stop (or nil if self{} is not stopped).

termsig

  • stat.termsig →fixnum or nil

Returns the number of the signal that caused stat to terminate (or nil if self{} was not terminated by an uncaught signal).

to_i

  • stat.to_i →fixnum

Returns the bits in stat as a Fixnum. Poking around in these bits is platform dependent.

fork { exit 0xab } # => 24079

Process.wait # => 24079

sprintf('%04x', $?.to_i) # => "ab00"

to_s

  • stat.to_s →string

Equivalent to stat.to_i.to_s.

Module Process::Sys

Process::Sys provides system call--level access to the process user and group environment. Many of the calls are aliases of those in the Process module and are packaged here for completeness. See also Process::GID and Process::UID for a higher-level (and more portable) interface.

Process::Sys: Module methods

getegid

  • Process::Sys.getegid →gid

Returns the effective group ID for this process. Synonym for Process.egid.

geteuid

  • Process::Sys.getugid →uid

Returns the effective user ID for this process. Synonym for Process.euid.

getgid

  • Process::Sys.getgid →gid

Returns the group ID for this process. Synonym for Process.gid.

getuid

  • Process::Sys.getuid →uid

Returns the user ID for this process. Synonym for Process.uid.

issetugid

  • Process::Sys.issetugid → true or false

Returns true if this process was made setuid or setgid as a result of the last execve() system call and returns false if not. Raises NotImplementedError on systems that don’t support issetugid(2).

setegid

  • Process::Sys.setegid(gid )

Sets the effective group ID to gid, failing if the underlying system call fails. Raises NotImplementedError on systems that don’t support setegid(2).

seteuid

  • Process::Sys.seteuid(uid )

Sets the effective user ID to uid, failing if the underlying system call fails. Raises NotImplementedError on systems that don’t support seteuid(2).

setgid

  • Process::Sys.setgid(gid )

Sets the group ID to gid, failing if the underlying system call fails. Raises NotImplementedError on systems that don’t support setgid(2).

setregid

  • Process::Sys.setregid(rgid, egid )

Sets the real and effective group IDs to rgid and egid, failing if the underlying system call fails. Raises NotImplementedError on systems that don’t support setregid(2).

setresgid

  • Process::Sys.setresgid(rgid, egid, sgid )

Sets the real, effective, and saved group IDs to rgid, egid, and sgid, failing if the underlying system call fails. Raises NotImplementedError on systems that don’t support setresgid(2).

setresuid

  • Process::Sys.setresuid(ruid, euid, suid )

Sets the real, effective, and saved user IDs to ruid, euid, and suid, failing if the underlying system call fails. Raises NotImplementedError on systems that don’t support setresuid(2).

setreuid

  • Process::Sys.setreuid(ruid, euid )

Sets the real and effective user IDs to ruid and euid, failing if the underlying system call fails. Raises NotImplementedError on systems that don’t support setreuid(2).

setrgid

  • Process::Sys.setrgid(rgid )

Sets the real group ID to rgid, failing if the underlying system call fails. Raises NotImplementedError on systems that don’t support setrgid(2).

setruid

  • Process::Sys.setruid(ruid )

Sets the real user ID to ruid, failing if the underlying system call fails. Raises NotImplementedError on systems that don’t support setruid(2).

setuid

  • Process::Sys.setuid(uid )

Sets the user ID to uid, failing if the underlying system call fails. Raises NotImplementedError on systems that don’t support setuid(2).

Module Process::UID

Provides a higher-level (and more portable) interface to the underlying operating system’s concepts of real, effective, and saved user IDs. For more information, see the introduction to Process::GID.

Process::UID: Module methods

change_privilege

  • Process::UID.change_privilege(uid ) → uid

Sets the real, effective, and saved user IDs to uid, raising an exception on failure (in which case the state of the IDs is not known). Not compatible with Process.uid=.

eid

  • Process::UID.eid →euid

Returns the effective user ID for this process. Synonym for Process.euid.

eid=

  • Process::UID.eid =euid

Synonym for Process::UID.grant_privilege.

grant_privilege

  • Process::UID.grant_privilege(euid ) → euid

Sets the effective user ID to euid, raising an exception on failure. On some environments this may also change the saved user ID.

re_exchange

  • Process::UID.re_exchange →euid

Exchanges the real and effective user IDs, setting the saved user ID to the new effective user ID. Returns the new effective user ID.

re_exchangeable?

  • Process::UID.re_exchangeable → true or false

Returns true if real and effective user IDs can be exchanged on the host operating system and returns false otherwise.

rid

  • Process::UID.rid →uid

Returns the real user ID for this process. Synonym for Process.uid.

sid_available?

  • Process::UID.sid_available? → true or false

Returns true if the underlying platform supports saved user IDs and returns false otherwise. Currently, Ruby assumes support if the operating system has setresuid(2) or seteuid(2) calls or if the configuration includes the POSIX_SAVED_IDS flag.

switch

  • Process::UID.switch →euid
  • Process::UID.switch { … } →obj

Handles the toggling of user privilege. In the block form, automatically toggles the IDs back when the block terminates (as long as the block doesn’t use other Process::UID calls to interfere). Without a block, returns the original effective user ID.

Class Range < Object

A Range represents an interval—a set of values with a start and an end. Ranges may be constructed using the s..e and s...e literals or using Range.new. Ranges constructed using .. run from the start to the end inclusively. Those created using ... exclude the end value. When used as an iterator, ranges return each value in the sequence.

(-1..-5).to_a # => []

(-5..-1).to_a # => [-5, -4, -3, -2, -1]

('a'..'e').to_a # => ["a", "b", "c", "d", "e"]

('a'...'e').to_a # => ["a", "b", "c", "d"]

Ranges can be constructed using objects of any type, as long as the objects can be compared using their <=> operator and they support the succ method to return the next object in sequence.

class Xs # represent a string of 'x's

include Comparable

attr :length

def initialize(n)

@length = n

end

def succ

Xs.new(@length + 1)

end

def <=>(other)

@length <=> other.length

end

def inspect

'x' * @length

end

end

r = Xs.new(3)..Xs.new(6) # => xxx..xxxxxx

r.to_a # => [xxx, xxxx, xxxxx, xxxxxx]

r.member?(Xs.new(5)) # => true

In the previous code example, class Xs includes the Comparable module. This is because Enumerable#member? checks for equality using == . Including Comparable ensures that the == method is defined in terms of the <=> method implemented in Xs.

Mixes in

Enumerable

all?, any?, chunk, collect, collect_concat, count, cycle, detect, drop, drop_while, each_cons, each_entry, each_slice, each_with_index, each_with_object, entries, find, find_all, find_index, first, flat_map, grep, group_by, include?, inject, lazy, map, max, max_by, member?, min, min_by, minmax, minmax_by, none?, one?, partition, reduce, reject, reverse_each, select, slice_before, sort, sort_by, take, take_while, to_a, zip

Range: Class methods

new

  • Range.new(start, end, exclusive=false ) → rng

Constructs a range using the given start and end. If the third parameter is omitted or is false, the range will include the end object; otherwise, it will be excluded.

Range: Instance methods

==

  • rng== objtrue or false

Returns true if obj is a range whose beginning and end are the same as those in rng (compared using ==) and whose exclusive flag is the same as rng.

===

  • rng=== valtrue or false

If rng excludes its end, returns rng.start val < rng.end. If rng is inclusive, returns rng.start val rng.end. Note that this implies that val need not be a member of the range itself (for example, a float could fall between the start and end values of a range of integers). Implemented by calling include? . Conveniently, the === operator is used by case statements.

case 74.95

when 1...50 then puts "low"

when 50...75 then puts "medium"

when 75...100 then puts "high"

end

Produces:

medium

begin

  • rng.begin →obj

Returns the first object of rng.

bsearch

  • rng.bsearch { |val| … } →obj or nil>

The same basic functionality as Array#bsearch. However, the range variant is typically used to search for something outside the range itself. For example, the range values could be used as a parameter to a function, or to index into some other collection. Remember though that the value returned by that function or collection must increase as its parameter increases.«2.0»

Here’s a (poor) method that finds the number of binary digits required to represent a number:

def bit_size(n)

(0...(8*n.size)).bsearch { |bitno| (1 << bitno) > n }

end

[ 0x05, 0x50, 0x5a010000 ].each do |n|

printf "Bitsize of %b is %d\n", n, bit_size(n)

end

Produces:

Bitsize of 101 is 3

Bitsize of 1010000 is 7

Bitsize of 1011010000000010000000000000000 is 31

And here’s a somewhat surprising example that finds x for which sin(x) equals 0.5.

(0.0..Math::PI/2).bsearch {|x| Math.sin(x) >= 0.5} # => 0.5235987755982989

On my box, it has the answer correct to 1% within 14 iterations, and takes 62 iterations to find it to the limit of Float precision.

cover?

  • rng.cover?(obj ) → true or false

Returns true if obj lies between the start and end of the range. For ranges defined with min..max, this means min obj max. For ranges defined with min...max, it means min obj < max.

(1..10).cover?(0) # => false

(1..10).cover?(5) # => true

(1..10).cover?(9.5) # => true

(1..10).cover?(10) # => true

(1...10).cover?(10) # => false

each

  • rng.each { |i| … } →rng

Iterates over the elements rng, passing each in turn to the block. Successive elements are generated using the succ method.

(10..15).each do |n|

print n, ' '

end

Produces:

10 11 12 13 14 15

end

  • rng.end →obj

Returns the object that defines the end of rng.

(1..10).end # => 10

(1...10).end # => 10

eql?

  • rng.eql?(obj) → true or false

Returns true if obj is a range whose beginning and end are the same as those in rng (compared using eql? ) and whose exclusive flag is the same as rng.

exclude_end?

  • rng.exclude_end? → true or false

Returns true if rng excludes its end value.

first

  • rng.first(n = 1 ) → obj or array

Returns the first (or first n) elements of rng.

('aa'..'bb').first # => "aa"

('aa'..'bb').first(5) # => ["aa", "ab", "ac", "ad", "ae"]

include?

  • rng.include?(val ) → true or false

Returns true if val is one of the values in rng (that is, if Range#each would return val at some point). If the range is defined to span numbers, this method returns true if the value lies between the start and end of the range, even if it is not actually a member (that is, it has the same behavior asRange#cover?). Otherwise, the parameter must be a member of the range.

r = 1..10

r.include?(5) # => true

r.include?(5.5) # => true

r.include?(10) # => true

r = 1...10

r.include?(10) # => false

r = 'a'..'z'

r.include?('b') # => true

r.include?('ruby') # => false

last

  • rng.last(n = 1 ) → obj or array

Returns the last (or last n) elements of rng.

('aa'..'bb').last # => "bb"

('aa'..'bb').last(5) # => ["ax", "ay", "az", "ba", "bb"]

max

  • rng.max →obj
  • rng.max { |a,b| … } →obj

Returns the maximum value in the range. The block is used to compare values if present.

(-3..2).max # => 2

(-3..2).max {|a,b| a*a <=> b*b } # => -3

member?

  • rng.member?(val ) → true or false

Synonym for Range#include?.

min

  • rng.min →obj
  • rng.min { |a,b| … } →obj

Returns the minimum value in the range. The block is used to compare values if present.

(-3..2).min # => -3

(-3..2).min {|a,b| a*a <=> b*b } # => 0

size

  • rng.size →int or nil

Returns the number of elements in rng. In Ruby 2.0, only works for ranges of integers.«2.0»

(1..26).size # => 26

('a'..'z').size # => nil

step

  • rng.step(n=1 ) <obj> → rng or enum

Iterates over rng, passing each nth element to the block. If the range contains numbers, addition by one is used to generate successive elements. Otherwise, step invokes succ to iterate through range elements. If no block is given, an enumerator is returned. The following code uses class Xs defined at the start of this section:

range = Xs.new(1)..Xs.new(10)

range.step(2) {|x| p x}

enum = range.step(3)

p enum.to_a

Produces:

x

xxx

xxxxx

xxxxxxx

xxxxxxxxx

[x, xxxx, xxxxxxx, xxxxxxxxxx]

Here’s step with numbers:

(1..5).step(1).to_a # => [1, 2, 3, 4, 5]

(1..5).step(2).to_a # => [1, 3, 5]

(1..5).step(1.5).to_a # => [1.0, 2.5, 4.0]

(1.0..5.0).step(1).to_a # => [1.0, 2.0, 3.0, 4.0, 5.0]

(1.0..5.0).step(2).to_a # => [1.0, 3.0, 5.0]

(1.0..5.0).step(1.5).to_a # => [1.0, 2.5, 4.0]

Class Random < Object

A random number generator, based on the Mersenne Twister MT19937 (the period is 219937-1). The global rand and srand methods are wrappers for this class.

Random: Class methods

new

  • Random.new(<seed=Random.new_seed> ) → rand

Creates a new random random number generator with the given seed. The seed will be converted to an integer.

new_seed

  • Random.new_seed →bignum

Returns a number that can be used as a seed. The value is derived from a system random number generator if available; otherwise, it combines the time, the process ID, and a sequence number.

Random.new_seed # => 205460400778463129775182461758071944669

rand

  • Random.rand(max=0 ) → number
  • Random.rand(range ) → number

Synonym for Object#rand.

srand

  • Random.rand(seed ) → old_seed

Synonym for Object#srand.

Random: Instance methods

bytes

  • rand.bytes(length ) → string

Returns a binary-encoded string, length bytes long, containing random bits.

rand = Random.new

rand.bytes(10) # => "T\xAEP\xD5\0\xAD\x7F\x84b\xC9"

rand

  • rand.rand(max=0 ) → number
  • rand.rand(range ) → number

Converts max to an integer using max1 = max.to_i.abs. If the result is zero or nil, 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. If a range is passed, return a random number in that range.

seed

  • rand.seed →bignum

Returns the seed for this random number generator.

Class Rational < Numeric

Rational numbers are expressed as the ratio of two integers. When the denominator exactly divides the numerator, a rational number is effectively an integer. Rationals allow exact representation of fractional numbers, but some real values cannot be expressed exactly and so cannot be represented as rationals.

Class Rational is normally relatively independent of the other numeric classes, in that the result of dividing two integers with the / operator will normally be a (truncated) integer (the quo method will always return a rational result). However, if the mathn library is loaded into a program, integer division may generate a Rational result. Also see the rational library for additional methods on rational numbers.

r1 = Rational("1/2") # => 1/2

r2 = 4.quo(5) # => 4/5

r1 * r2 # => 2/5

Rational: Instance methods

Arithmetic operations

Performs various arithmetic operations on rat.

rat

+

numeric

Addition

rat

-

numeric

Subtraction

rat

*

numeric

Multiplication

rat

/

numeric

Division

rat

%

numeric

Modulo

rat

**

numeric

Exponentiation

rat

-@

Unary minus

Comparisons

Compares rat to other numbers: < , <= , == , >= , and > .

<=>

  • rat<=> numeric → -1, 0, +1, or nil

Comparison—Returns -1, 0, or +1 depending on whether rat is less than, equal to, or greater than numeric. Although Rational’s grandparent mixes in Comparable, Rational does not use that module for performing comparisons, instead implementing the comparison operators explicitly.

Rational("4/2") <=> Rational("98/49") # => 0

Rational("3/4") <=> 41 # => -1

Rational("0") <=> 0.0 # => 0

==

  • rat== numeric

Returns true if rat has the same value as numeric. Comparisons against integers and rational numbers are exact; comparisons against floats first convert rat to a float.

ceil

  • rat.ceil →numeric

Returns the smallest integer greater than or equal to rat.

Rational("22/7").ceil # => 4

Rational("-22/7").ceil # => -3

denominator

  • rat.denominator →a_number

Returns the denominator of rat.

Rational("2/3").denominator # => 3

fdiv

  • rat.fdiv(numeric ) → float

Returns the floating-point result of dividing rat by numeric.

Rational("11/2") / 2 # => 11/4

Rational("11/2").fdiv 2 # => 2.75

floor

  • rat.floor →numeric

Returns the largest integer less than or equal to rat.

Rational("22/7").floor # => 3

Rational("-22/7").floor # => -4

numerator

  • rat.numerator →a_number

Returns the numerator of rat.

Rational("2/3").numerator # => 2

quo

  • rat.quo(numeric ) → numeric

Synonym for Rational#/.

rationalize

  • rat.rationalize →rat
  • rat.rationalize(epsilon ) → rational

With no argument, returns rat; otherwise, returns a new Rational with the given precision.

r = Math::PI.to_r # => (884279719003555/281474976710656)

r.rationalize # => (884279719003555/281474976710656)

r.rationalize(0.01) # => (22/7)

round

  • rat.round →numeric

Rounds rat to the nearest integer.

Rational("22/7").round # => 3

Rational("-22/7").round # => -3

to_f

  • rat.to_f →float

Returns the floating-point representation of rat.

Rational("37/4").to_f # => 9.25

to_i

  • rat.to_i →integer

Returns the truncated integer value of rat.

Rational("19/10").to_i # => 1

Rational("-19/10").to_i # => -1

to_r

  • rat.to_r →rat

Returns rat.

truncate

  • rat.truncate →numeric

Returns rat truncated to an integer.

Rational("22/7").truncate # => 3

Rational("-22/7").truncate # => -3

Class Regexp < Object

A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /.../ and %r{...} literals and using the Regexp.new constructor. See the reference on in Regular Expressions for more details.

Constants

EXTENDED

Ignores spaces and newlines in regexp

IGNORECASE

Matches are case insensitive

MULTILINE

Newlines treated as any other character

Regexp: Class methods

compile

  • Regexp.compile(pattern <, options lang> ) → rxp

Synonym for Regexp.new.

escape

  • Regexp.escape(string ) → escaped_string

Escapes any characters that would have special meaning in a regular expression. For any string, Regexp.new(Regexp.escape(str)) =~ str will be true.

Regexp.escape('\\[]*?{}.') # => \\\[\]\*\?\{\}\.

last_match

  • Regexp.last_match →match
  • Regexp.last_match(int ) → string

The first form returns the MatchData object generated by the last successful pattern match. This is equivalent to reading the global variable $~. MatchData has its own reference.

The second form returns the nth field in this MatchData object.

/c(.)t/ =~ 'cat' # => 0

Regexp.last_match # => #<MatchData "cat" 1:"a">

Regexp.last_match(0) # => "cat"

Regexp.last_match(1) # => "a"

Regexp.last_match(2) # => nil

new

  • Regexp.new(string <, options lang> ) → rxp
  • Regexp.new(regexp ) → new_regexp

Constructs a new regular expression from the string or the regexp. In the latter case, that regexp’s options are propagated, and new options may not be specified. If options is a number, it should be one or more of Regexp::EXTENDED, Regexp::IGNORECASE, or Regexp::MULTILINE, or-ed together. Otherwise, if the options parameter is not nil, the regexp will be case insensitive. The lang can be set to "N" or "n" to force the regular expression to have ASCII-8BIT encoding;[121] otherwise, the encoding of the string determines the encoding of the regular expression.

# encoding: utf-8

r1 = Regexp.new('^[a-z]+:\\s+\w+') # => /^[a-z]+:\s+\w+/

r2 = Regexp.new('cat', true) # => /cat/i

r3 = Regexp.new('dog', Regexp::EXTENDED) # => /dog/x

r4 = Regexp.new(r2) # => /cat/i

r5 = Regexp.new("∂elta") # => /∂elta/

r1.encoding # => #<Encoding:US-ASCII>

r5.encoding # => #<Encoding:UTF-8>

quote

  • Regexp.quote(string ) → escaped_string

Synonym for Regexp.escape.

try_convert

  • Regexp.try_convert(obj ) → a_regexp or nil

If obj is not already a regular expression, attempts to convert it to one by calling its to_regexp method. Returns nil if no conversion could be made.

Regexp.try_convert("cat") # => nil

class String

def to_regexp

Regexp.new(self)

end

end

Regexp.try_convert("cat") # => /cat/

union

  • Regexp.union(<pattern>* ) → a_regexp

Returns a regular expression that will match any of the given patterns. With no patterns, produces a regular expression that will never match. If a pattern is a string, it will be given the default regular expression options. If a pattern is a regular expression, its options will be honored in the final pattern. The patterns may also be passed in a single array.

Regexp.union("cat") # => /cat/

Regexp.union("cat", "dog") # => /cat|dog/

Regexp.union(%w{ cat dog }) # => /cat|dog/

Regexp.union("cat", /dog/i) # => /cat|(?i-mx:dog)/

Regexp: Instance methods

==

  • rxp== other_regexptrue or false

Equality—Two regexps are equal if their patterns are identical, they have the same character set code, and their casefold? values are the same.

/abc/ == /abc/x # => false

/abc/ == /abc/i # => false

/abc/u == /abc/n # => false

===

  • rxp=== stringtrue or false

Case Equality—Like Regexp#=~ but accepts nonstring arguments (returning false). Used in case statements.

a = "HELLO"

case a

when /\A[a-z]*\z/; print "Lower case\n"

when /\A[A-Z]*\z/; print "Upper case\n"

else print "Mixed case\n"

end

Produces:

Upper case

=~

  • rxp=~ stringint or nil

Match—Matches rxp against string, returning the offset of the start of the match or nil if the match failed. Sets $~ to the corresponding MatchData or nil.

/SIT/ =~ "insensitive" # => nil

/SIT/i =~ "insensitive" # => 5

~

  • ~rxpint or nil

Match—Matches rxp against the contents of $_. Equivalent to rxp =~ $_. You should be ashamed if you use this:

$_ = "input data"

~ /at/ # => 7

casefold?

  • rxp.casefold? → true or false

Returns the value of the case-insensitive flag. Merely setting the i option inside rxp does not set this flag.

/cat/.casefold? # => false

/cat/i.casefold? # => true

/(?i:cat)/.casefold? # => false

encoding

  • rxp.encoding →an_encoding

Returns the character encoding for the regexp.

/cat/.encoding # => #<Encoding:US-ASCII>

/cat/s.encoding # => #<Encoding:Windows-31J>

/cat/u.encoding # => #<Encoding:UTF-8>

fixed_encoding?

  • rxp.fixed_encoding? → true or false

A regular expression containing only 7-bit characters can be matched against a string in any encoding. In this case, fixed_encoding? returns false. Otherwise, it returns true.

/cat/.fixed_encoding? # => false

/cat/s.fixed_encoding? # => true

/cat/u.fixed_encoding? # => true

match

  • rxp.match(string, offset=0 ) → match or nil
  • rxp.match(string, offset=0 ) { |match| … } → obj

Returns a MatchData object describing the match or nil if there was no match. This is equivalent to retrieving the value of the special variable $~ following a normal match. The match process will start at offset into string. If a block is given and the match is successful, the block will be invoked with the MatchData object, and the value returned by the block will be the value returned by match .

md = /(.)(d)(.)/.match("abcdefabcdef")

md # => #<MatchData "cde" 1:"c" 2:"d" 3:"e">

md[1] # => "c"

md.begin(1) # => 2

md = /(.)(d)(.)/.match("abcdedcba", 4)

md # => #<MatchData "edc" 1:"e" 2:"d" 3:"c">

md.begin(1) # => 4

result = /(...)...(...)/.match("catanddog") do |md|

md[1] + "&" + md[2]

end

result # => "cat&dog"

named_captures

  • rxp.named_captures →hash

Returns a hash whose keys are the names of captures and whose values are each an array containing the number of the capture in rxp.

/(?<a>.).(?<b>.)/.named_captures # => {"a"=>[1], "b"=>[2]}

/(?<a>.)(.)(?<b>.)/.named_captures # => {"a"=>[1], "b"=>[2]}

/(?<a>.)(?<b>.)(?<a>.)/.named_captures # => {"a"=>[1, 3], "b"=>[2]}

names

  • rxp.names →array

Returns an array containing the names of captures in rxp.

/(.)(.)(.)/.names # => []

/(?<first>.).(?<last>.)/.names # => ["first", "last"]

options

  • rxp.options →int

Returns the set of bits corresponding to the options used when creating this regexp (see Regexp.new for details). Note that additional bits may be set in the returned options; these are used internally by the regular expression code. These extra bits are ignored if the options are passed toRegexp.new.

# Let's see what the values are...

Regexp::IGNORECASE # => 1

Regexp::EXTENDED # => 2

Regexp::MULTILINE # => 4

/cat/.options # => 0

/cat/ix.options # => 3

Regexp.new('cat', true).options # => 1

Regexp.new('cat', 0, 'n').options # => 32

r = /cat/ix

Regexp.new(r.source, r.options) # => /cat/ix

source

  • rxp.source →string

Returns the original string of the pattern.

/ab+c/ix.source # => "ab+c"

to_s

  • rxp.to_s →string

Returns a string containing the regular expression and its options (using the (?xx:yyy) notation). This string can be fed back into Regexp.new to a regular expression with the same semantics as the original. (However, Regexp#== may not return true when comparing the two, because the source of the regular expression itself may differ, as the example shows.) Regexp#inspect produces a generally more readable version of rxp.

r1 = /ab+c/ix # => /ab+c/ix

s1 = r1.to_s # => "(?ix-m:ab+c)"

r2 = Regexp.new(s1) # => /(?ix-m:ab+c)/

r1 == r2 # => false

r1.source # => "ab+c"

r2.source # => "(?ix-m:ab+c)"

Module Signal

Many operating systems allow signals to be sent to running processes. Some signals have a defined effect on the process, and others may be trapped at the code level and acted upon. For example, your process may trap the USR1 signal and use it to toggle debugging, and it may use TERM to initiate a controlled shutdown.

pid = fork do

Signal.trap("USR1") do

$debug = !$debug

puts "Debug now: #$debug"

end

Signal.trap(:TERM) do # symbols work too...

puts "Terminating..."

exit

end

# . . . do some work . . .

end

Process.detach(pid)

# Controlling program:

Process.kill("USR1", pid)

# ...

Process.kill(:USR1, pid)

# ...

Process.kill("TERM", pid)

Produces:

Debug now: true

Debug now: false

Terminating...

The list of available signal names and their interpretation is system dependent. Signal delivery semantics may also vary between systems; in particular, signal delivery may not always be reliable.

Signal: Module methods

list

  • Signal.list →hash

Returns a list of signal names mapped to the corresponding underlying signal numbers.

Signal.list # => {"ABRT"=>6, "ALRM"=>14, "BUS"=>10, "CHLD"=>20, "CLD"=>20,

# .. "CONT"=>19, "EMT"=>7, "EXIT"=>0, "FPE"=>8, "HUP"=>1, "ILL"=>4,

# .. "INFO"=>29, "INT"=>2, "IO"=>23, "IOT"=>6, "KILL"=>9, "PIPE"=>13,

# .. "PROF"=>27, "QUIT"=>3, "SEGV"=>11, "STOP"=>17, "SYS"=>12,

# .. "TERM"=>15, "TRAP"=>5, "TSTP"=>18, "TTIN"=>21, "TTOU"=>22,

# .. "URG"=>16, "USR1"=>30, "USR2"=>31, "VTALRM"=>26, "WINCH"=>28,

# .. "XCPU"=>24, "XFSZ"=>25}

signame

  • Signal.signame(num ) → string

Return the (abbreviated) name of the signal with the given number. An ArgumentError is raised if the number does not correspond to a signal.«2.0»

Signal.signame(1) # => "HUP"

Signal.signame(15) # => "TERM"

trap

  • Signal.trap(signal, command ) → obj
  • Signal.trap(signal ) { … } → obj

Specifies the handling of signals. The first parameter is a signal name (a string or symbol 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 nil, the string IGNORE or SIG_IGN, or the empty string, 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 cannot be used with the signals BUS, FPE, ILL, SEGV, or VTALRM.«2.0»

trap returns the previous handler for the given signal.

Signal.trap(0, lambda { |signo| puts "exit pid #{$$} with #{signo}" })

Signal.trap("CLD") { |signo| puts "Child died (#{signo})" }

if fork # parent

do_something # ...

else

puts "In child, PID=#{$$}"

end

Produces:

In child, PID=24189

exit pid 24189 with 0

Child died (20)

exit pid 24188 with 0

Note that you must specify a block taking a parameter if you use lambda to create the proc object.

Class String < Object

A String object holds and manipulates a sequence of characters. String objects may be created using String.new or as literals (see Strings).

Because of aliasing issues, users of strings should be aware of the methods that modify the contents of a String object. Typically, methods with names ending in ! modify their receiver, while those without a ! return a new String. However, exceptions exist, such as String#[]=.

In this description, I try to differentiate between the bytes in a string and the characters in a string. Internally, a string is a sequence of 8-bit bytes. These are represented externally as small Fixnums. At the same time, these byte sequences are interpreted as a sequence of characters. This interpretation is controlled by the encoding of the string. In some encodings (such as US-ASCII and ISO-8859), each byte corresponds to a single character. In other encodings (such as UTF-8), a varying number of bytes comprise each character.

As of Ruby 1.9, String no longer mixes in Enumerable.

Mixes in

Comparable

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

String: Class methods

new

  • String.new(val="" ) → str

Returns a new string object containing a copy of val (which should be a String or implement to_str ). Note that the new string object is created only when one of the strings is modified.

str1 = "wibble"

str2 = String.new(str1)

str1.object_id # => 70198849846720

str2.object_id # => 70198849846680

str1[1] = "o"

str1 # => "wobble"

str2 # => "wibble"

try_convert

  • String.try_convert(obj ) → a_string or nil

If obj is not already a string, attempts to convert it to one by calling its to_str method. Returns nil if no conversion could be made.

String.try_convert("cat") # => "cat"

String.try_convert(0xbee) # => nil

String: Instance methods

%

  • str% argstring

Format—Uses str as a format specification and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array containing the values to be substituted. See Object#sprintf for details of the format string.

puts "%05d" % 123

puts "%-5s: %08x" % [ "ID", self.object_id ]

puts "%-5<name>s: %08<value>x" % { name: "ID", value: self.object_id }

Produces:

00123

ID : 3ff795471248

ID : 3ff795471248

*

  • str* intstring

Copies—Returns a new String containing int copies of the receiver.

"Ho! " * 3 # => "Ho! Ho! Ho! "

+

  • str+ stringstring

Concatenation—Returns a new String containing string concatenated to str. If both strings contain non-7-bit characters, their encodings must be compatible.

"Hello from " + "RubyLand" # => "Hello from RubyLand"

<<

  • str<< fixnumstr
  • str<< objstr

Append—Concatenates the given object to str. If the object is a Fixnum, it is considered to be a codepoint in the encoding of str and converted to the appropriate character before being appended.

a = "hello world"

a.force_encoding("utf-8")

a << 33 # => "hello world!"

a << " Says the " # => "hello world! Says the "

a << 8706 # => "hello world! Says the ∂"

a << "og" # => "hello world! Says the ∂og"

<=>

  • str<=> other_string → -1, 0, +1, or nil

Comparison—Returns -1 if str is less than, 0 if str is equal to, and +1 if str is greater than other_string. If the strings are of different lengths and the strings are equal when compared to the shortest length, then the longer string is considered greater than the shorter one. In older versions of Ruby, setting $= allowed case-insensitive comparisons; you must now use String#casecmp.

<=> is the basis for the methods < , <= , > , >= , and between? , included from module Comparable. The method String#== does not use Comparable#==.

"abcdef" <=> "abcde" # => 1

"abcdef" <=> "abcdef" # => 0

"abcdef" <=> "abcdefg" # => -1

"abcdef" <=> "ABCDEF" # => 1

==

  • str== objtrue or false

Equality—If obj is a String, returns true if str has the same encoding, length, and content as obj; returns false otherwise. If obj is not a String but responds to to_str , returns obj == str; otherwise, returns false.

"abcdef" == "abcde" # => false

"abcdef" == "abcdef" # => true

=~

  • str=~ regexpint or nil

Match—Equivalent to regexp =~ str. Prior versions of Ruby permitted an arbitrary operand to =~ ; this is now deprecated. Returns the position where the match starts or returns nil if there is no match or if regexp is not a regular expression.[122]

"cat o' 9 tails" =~ /\d/ # => 7

"cat o' 9 tails" =~ 9 # => nil

"cat o' 9 tails" =~ "\d"

Produces:

from prog.rb:1:in `<main>'

prog.rb:1:in `=~': type mismatch: String given (TypeError)

[ ]

  • str[int ] → string or nil
  • str[int, int ] → string or nil
  • str[range ] → string or nil
  • str[regexp ] → string or nil
  • str[regexp, int ] → string or nil
  • str[regexp, name ] → string or nil
  • str[string ] → string or nil

Element Reference—If passed a single int, returns the character at that position. (Prior to Ruby 1.9, an integer character code was returned.) If passed two ints, returns a substring starting at the offset given by the first, and a length given by the second. If given a range, a substring containing characters at offsets given by the range is returned. In all three cases, if an offset is negative, it is counted from the end of str. Returns nil if the initial offset falls outside the string and the length is not given, the length is negative, or the beginning of the range is greater than the end.

If regexp is supplied, the matching portion of str is returned. If a numeric parameter follows the regular expression, that component of the MatchData is returned instead. If a String is given, that string is returned if it occurs in str. If a name follows the regular expression, the corresponding named match is returned. In all cases, nil is returned if there is no match.

a = "hello there"

a[1] # => "e"

a[1,3] # => "ell"

a[1..3] # => "ell"

a[1...3] # => "el"

a[-3,2] # => "er"

a[-4..-2] # => "her"

a[-2..-4] # => ""

a[/[aeiou](.)\1/] # => "ell"

a[/[aeiou](.)\1/, 0] # => "ell"

a[/[aeiou](.)\1/, 1] # => "l"

a[/[aeiou](.)\1/, 2] # => nil

a[/(..)e/] # => "the"

a[/(..)e/, 1] # => "th"

a[/(?<vowel>[aeiou])/, :vowel] # => "e"

a["lo"] # => "lo"

a["bye"] # => nil

[ ]=

  • str[int ] = string
  • str[int, int ] = string
  • str[range ] = string
  • str[regexp ] = string
  • str[regexp, int ] = string
  • str[string ] = string}

Element Assignment—Replaces some or all of the content of str. The portion of the string affected is determined using the same criteria as String#[ ]. If the replacement string is not the same length as the text it is replacing, the string will be adjusted accordingly. If the regular expression or string is used because the index doesn’t match a position in the string, IndexError is raised. If the regular expression form is used, the optional second int allows you to specify which portion of the match to replace (effectively using the MatchData indexing rules). The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment.

a = "hello"

a[2] = "u"

(a → "heulo")

a[2, 4] = "xyz"

(a → "hexyz")

a[-4, 2] = "xyz"

(a → "hxyzlo")

a[2..4] = "xyz"

(a → "hexyz")

a[-4..-2] = "xyz"

(a → "hxyzo")

a[/[aeiou](.)\1(.)/] = "xyz"

(a → "hxyz")

a[/[aeiou](.)\1(.)/, 1] = "xyz"

(a → "hexyzlo")

a[/[aeiou](.)\1(.)/, 2] = "xyz"

(a → "hellxyz")

a["l"] = "xyz"

(a → "hexyzlo")

a["ll"] = "xyz"

(a → "hexyzo")

a[2, 0] = "xyz"

(a → "hexyzllo")

ascii_only?

  • str.ascii_only? → true or false

Returns true if the string contains no characters with a character code greater than 127 (that is, it contains only 7-bit ASCII characters).

# encoding: utf-8

"dog".ascii_only? # => true

"∂og".ascii_only? # => false

"\x00 to \x7f".ascii_only? # => true

b

  • str.b →string

Returns a copy of the contents of str with ASCII-8BIT encoding. This is a convenient way to get to the byte values of any string.«2.0»

str = "∂øg"

str.length # => 3

bstr = str.b

bstr.length # => 6

bytes

  • str.bytes →enum | array
  • str.bytes { |byte| … } →str

Returns an enumerator (Ruby 1.9) or array (Ruby 2.0)«2.0» for the bytes (integers in the range 0 to 255) in str. With a block, passes each byte to the block and returns the original string. See also String#codepoints and #chars .

# encoding: utf-8

"dog".bytes # => [100, 111, 103]

"∂og".bytes # => [226, 136, 130, 111, 103]

result = []

"∂og".bytes {|b| result << b } # => "∂og"

result # => [226, 136, 130, 111, 103]

bytesize

  • str.bytesize →int

Returns the number of bytes (not characters) in str. See also String#length.

# encoding: utf-8

"dog".length # => 3

"dog".bytesize # => 3

"∂og".length # => 3

"∂og".bytesize # => 5

byteslice

  • str.byteslice(offset, length=1 ) → string or nil
  • str.byteslice(range ) → string or nil

Returns the string consisting of length bytes starting at byte position offset, or between the offsets given by the range. A negative offset counts from the end of the string. The returned string retains the encoding of str, but may not be valid in that encoding.

# encoding: utf-8

a = "∂dog"

a.bytes.to_a # => [226, 136, 130, 100, 111, 103]

a.byteslice(0) # => "\xE2"

a.byteslice(0, 2) # => "\xE2\x88"

a.byteslice(0, 3) # => "∂"

a.byteslice(-2, 2) # => "og"

a.byteslice(-2..-1) # => "og"

capitalize

  • str.capitalize →string

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

"hello world".capitalize # => "Hello world"

"HELLO WORLD".capitalize # => "Hello world"

"123ABC".capitalize # => "123abc"

capitalize!

  • str.capitalize! →str or nil

Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made.

a = "hello world"

a.capitalize! # => "Hello world"

a # => "Hello world"

a.capitalize! # => nil

casecmp

  • str.casecmp(string ) → -1, 0, +1

Case-insensitive version of String#<=>.

"abcdef".casecmp("abcde") # => 1

"abcdef".casecmp("abcdef") # => 0

"aBcDeF".casecmp("abcdef") # => 0

"abcdef".casecmp("abcdefg") # => -1

"abcdef".casecmp("ABCDEF") # => 0

center

  • str.center(int, pad=" " ) → string

If int is greater than the length of str, returns a new String of length int with str centered between the given padding (defaults to spaces); otherwise, returns str.

"hello".center(4) # => "hello"

"hello".center(20) # => "␣␣␣␣␣␣␣hello␣␣␣␣␣␣␣␣"

"hello".center(4, "_-^-") # => "hello"

"hello".center(20, "_-^-") # => "_-^-_-^hello_-^-_-^-"

"hello".center(20, "-") # => "-------hello--------"

chars

  • str.chars →enum | array
  • str.chars { |char| … } →str

Returns an enumerator (Ruby 1.9) or array (Ruby 2.0)«2.0» for the characters (single character strings) in str. With a block, passes each character to the block and returns the original string. See also String#bytes and String#codepoints.

# encoding: utf-8

"dog".chars.to_a # => ["d", "o", "g"]

"∂og".chars.to_a # => ["∂", "o", "g"]

result = []

"∂og".chars {|b| result << b } # => "∂og"

result # => ["∂", "o", "g"]

chr

  • str.chr →string

Returns the first character of str.

# encoding: utf-8

"dog".chr # => "d"

"∂og".chr # => "∂"

clear

  • str.clear →str

Removes the content (but not the associated encoding) of str.

# encoding: utf-8

str = "∂og"

str.clear # => ""

str.length # => 0

str.encoding # => #<Encoding:UTF-8>

chomp

  • str.chomp(rs=$/ ) → string

Returns a new String with the given record separator removed from the end of str (if present). If $/ has not been changed from the default Ruby record separator, then chomp also removes carriage return characters (that is, it will remove \n, \r, and \r\n).

"hello".chomp # => "hello"

"hello\n".chomp # => "hello"

"hello\r\n".chomp # => "hello"

"hello\n\r".chomp # => "hello\n"

"hello\r".chomp # => "hello"

"hello \n there".chomp # => "hello \n there"

"hello".chomp("llo") # => "he"

chomp!

  • str.chomp!(rs=$/ ) → str or nil

Modifies str in place as described for String#chomp, returning str or returning nil if no modifications were made.

chop

  • str.chop →string

Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, because it leaves the string unchanged if it doesn’t end in a record separator.

"string\r\n".chop # => "string"

"string\n\r".chop # => "string\n"

"string\n".chop # => "string"

"string".chop # => "strin"

"x".chop.chop # => ""

chop!

  • str.chop! →str or nil

Processes str as for String#chop, returning str or returning nil if str is the empty string. See also String#chomp!.

codepoints

  • str.codepoints →enum | array
  • str.codepoints { |integer| … } →str

Returns an enumerator (Ruby 1.9) or array (Ruby 2.0)«2.0» for the codepoints (integers representation of the characters) in str. With a block, passes each integer to the block and returns the original string. See also String#bytes and String#chars.

# encoding: utf-8

"dog".codepoints.to_a # => [100, 111, 103]

"∂og".codepoints.to_a # => [8706, 111, 103]

result = []

"∂og".codepoints {|b| result << b } # => "∂og"

result # => [8706, 111, 103]

concat

  • str.concat(int ) → str
  • str.concat(obj ) → str

Synonym for String#<<.

count

  • str.count(<string>+ ) → int

Each string parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str. Any parameter that starts with a caret (^) is negated. The sequence c1-c2 means all characters between c1 and c2.

a = "hello world"

a.count "lo" # => 5

a.count "lo", "o" # => 2

a.count "hello", "^l" # => 4

a.count "ej-m" # => 4

crypt

  • str.crypt(settings ) → string

Applies a one-way cryptographic hash to str by invoking the standard library function crypt . The argument is to some extent system dependent. On traditional Unix boxes, it is often a two-character salt string. On more modern boxes, it may also control things such as DES encryption parameters. See the man page for crypt(3) for details.

# standard salt

"secret".crypt("sh") # => "shRK3aVg8FsI2"

# On OSX: DES, 2 interactions, 24-bit salt

"secret".crypt("_...0abcd") # => "_...0abcdROn65JNDj12"

delete

  • str.delete(<string>+ ) → new_string

Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as String#count.

"hello".delete("l","lo") # => "heo"

"hello".delete("lo") # => "he"

"hello".delete("aeiou", "^e") # => "hell"

"hello".delete("ej-m") # => "ho"

delete!

  • str.delete!(<string>+ ) → str or nil

Performs a delete operation in place, returning str or returning nil if str was not modified.

a = "hello"

a.delete!("l","lo") # => "heo"

a # => "heo"

a.delete!("l") # => nil

downcase

  • str.downcase →string

Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. The operation is locale insensitive—only characters A to Z are affected. Multibyte characters are skipped.

"hEllO".downcase # => "hello"

downcase!

  • str.downcase! →str or nil

Replaces uppercase letters in str with their lowercase counterparts. Returns nil if no changes were made.

dump

  • str.dump →string

Produces a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped.

each_byte

  • str.each_byte →enum
  • str.each_byte { |byte| … } →str

Synonym for String#bytes. The each_byte form is falling out of favor.

each_char

  • str.each_char →enum
  • str.each_char { |char| … } →str

Synonym for String#chars. The each_char form is falling out of favor.

each_codepoint

  • str.each_codepoint →enum
  • str.each_codepoint { |integer| … } →str

Synonym for String#codepoints.

each_line

  • str.each_line(sep=$/ ) → enum
  • str.each_line(sep=$/ ) { |substr| … } → str}

Synonym for String#lines. The each_line form is falling out of favor.

empty?

  • str.empty? → true or false

Returns true if str has a length of zero.

"hello".empty? # => false

"".empty? # => true

encode

  • str.encode →a_string
  • str.encode(to_encoding <, options> ) → a_string
  • str.encode(to_encoding, from_encoding, <, options> ) → a_string

Transcodes str, returning a new string encoded with to_encoding. If no encoding is given, transcodes using default_internal encoding. The source encoding is either the current encoding of the string or from_encoding. May raise a RuntimeError if characters in the original string cannot be represented in the target encoding. The options parameter defines the behavior for invalid transcodings and other boundary conditions. It can be a hash (recommended) or an or-ing of integer values. Encodings can be passed as Encoding objects or as names.

Table 22. Options to encode and encode!

Option

Meaning

:replace => string

Specifies the string to use if :invalid or :undef options are present. If not specified, uFFFD is used for Unicode encodings and ? for others.

:invalid => :replace

Replaces invalid characters in the source string with the replacement string. If :invalid is not specified or nil, raises an exception.

:undef => :replace

Replaces characters that are not available in the destination encoding with the replacement string. If :undef not specified or nil, raises an exception.

:universal_newline => true

Converts crlf and cr line endings to lf.

:crlf_newline => true

Converts lf to crlf.

:cr_newline => true

Converts lf to cr.

:xml => :text | :attr

After encoding, escape characters that would otherwise have special meaning in XML PCDATA or attributes. In all cases, converts & to &, < to <, > to >, and undefined characters to a hexadecimal entity (&#xhh;). For :attr, also converts " to ".

# encoding: utf-8

ole_in_utf = "olé"

ole_in_utf.encoding # => #<Encoding:UTF-8>

ole_in_utf.dump # => "ol\u{e9}"

ole_in_8859 = ole_in_utf.encode("iso-8859-1")

ole_in_8859.encoding # => #<Encoding:ISO-8859-1>

ole_in_8859.dump # => "ol\xE9"

Using a default internal encoding of ISO-8859-1 and a source file encoding of UTF-8:

#!/usr/local/rubybook/bin/ruby -E:ISO-8859-1

# encoding: utf-8

utf_string = "olé"

utf_string.encoding # => #<Encoding:UTF-8>

iso_string = utf_string.encode

iso_string.encoding # => #<Encoding:ISO-8859-1>

Attempt to transcode a string with characters not available in the destination encoding:

# encoding: utf-8

utf = "∂og"

utf.encode("iso-8859-1")

Produces:

from prog.rb:3:in `<main>'

prog.rb:3:in `encode': U+2202 from UTF-8 to ISO-8859-1

(Encoding::UndefinedConversionError)

You can replace the character in error with something else:

# encoding: utf-8

utf = "∂og"

utf.encode("iso-8859-1", undef: :replace) # => "?og"

utf.encode("iso-8859-1", undef: :replace, replace: "X" ) # => "Xog"

encode!

  • str.encode! →str
  • str.encode!(to_encoding <, options> ) → str
  • str.encode!(to_encoding, from_encoding, <, options> ) → str

Transcodes str in place.

encoding

  • str.encoding →an_encoding

Returns the encoding of str.

# encoding: utf-8

"cat".encoding # => #<Encoding:UTF-8>

end_with?

  • str.end_with?(<suffix>+ ) → true or false

Returns true if str ends with any of the given suffixes.

"Apache".end_with?("ache") # => true

"ruby code".end_with?("python", "perl", "code") # => true

eql?

  • str.eql?(obj ) → true or false

Returns true if obj is a String with identical contents to str.

"cat".eql?("cat") # => true

force_encoding

  • str.force_encoding(encoding ) → str

Sets the encoding associated with str to encoding. Note that this does not change the underlying bytes in str—it simply tells Ruby how to interpret those bytes as characters.

# encoding: utf-8

∂og_in_bytes = [226, 136, 130, 111, 103] # utf-8 byte sequence

str = ∂og_in_bytes.pack("C*")

str.encoding # => #<Encoding:ASCII-8BIT>

str.length # => 5

str.force_encoding("utf-8")

str.encoding # => #<Encoding:UTF-8>

str.length # => 3

str # => "∂og"

getbyte

  • str.getbyte(offset ) → int or nil

Returns the byte at offset (starting from the end of the string if the offset is negative). Returns nil if the offset lies outside the string.

# encoding: utf-8

str = "∂og"

str.bytes.to_a # => [226, 136, 130, 111, 103]

str.getbyte(0) # => 226

str.getbyte(1) # => 136

str.getbyte(-1) # => 103

str.getbyte(99) # => nil

gsub

  • str.gsub(pattern, replacement ) → string
  • str.gsub(pattern ) { |match| … } → string
  • str.gsub(pattern ) → enum

Returns a copy of str with all occurrences of pattern replaced with either replacement or the value of the block. The pattern will typically be a Regexp; if it is a String, then no regular expression metacharacters will be interpreted (that is, /\d/ will match a digit, but ’\d’ will match a backslash followed by a d).

If a string is used as the replacement, special variables from the match (such as $& and $1) cannot be substituted into it, because substitution into the string occurs before the pattern match starts. However, the sequences \1, \2, and so on, may be used to interpolate successive numbered groups in the match, and \k<name> will substitute the corresponding named captures. These sequences are shown in the following table.

Table 23. Backslash sequences in substitution

Sequence

Text That Is Substituted

\1, \2, ... \9

The value matched by the nth grouped subexpression

\&

The last match

\‘

The part of the string before the match

\’

The part of the string after the match

\+

The highest-numbered group matched

\k<name>

The named capture

In the block form, the current match is passed in as a parameter, and variables such as $1, $2, $‘, $&, and $’ will be set appropriately. The value returned by the block will be substituted for the match on each call.

The result inherits any tainting in the original string or any supplied replacement string.

"hello".gsub(/[aeiou]/, '*') # => "h*ll*"

"hello".gsub(/([aeiou])/, '<\1>') # => "h<e>ll<o>"

"hello".gsub(/./) {|s| s[0].to_s + ' '} # => "h e l l o "

"hello".gsub(/(?<double>l)/, '-\k<double>-') # => "he-l--l-o"

If no block or replacement string is given, an enumerator is returned.

"hello".gsub(/../).to_a # => ["he", "ll"]

If a hash is given as the replacement, successive matched groups are looked up as keys, and the corresponding values are substituted into the string.

repl = Hash.new("?")

repl["a"] = "*"

repl["t"] = "T"

"cat".gsub(/(.)/, repl) # => "?*T"

gsub!

  • str.gsub!(pattern, replacement ) → string
  • str.gsub!(pattern ) { |match| … } → string
  • str.gsub!(pattern ) → enum

Performs the substitutions of String#gsub in place, returning str, or returning nil if no substitutions were performed. If no block or replacement string is given, an enumerator is returned.

hex

  • str.hex →int

Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error.

"0x0a".hex # => 10

"-1234".hex # => -4660

"0".hex # => 0

"wombat".hex # => 0

include?

  • str.include?(string ) → true or false

Returns true if str contains the given string.

"hello".include? "lo" # => true

"hello".include? "ol" # => false

"hello".include? ?h # => true

index

  • str.index(string <, offset> ) → int or nil
  • str.index(regexp <, offset> ) → int or nil

Returns the index of the first occurrence of the given substring or pattern in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e') # => 1

"hello".index('lo') # => 3

"hello".index('a') # => nil

"hello".index(/[aeiou]/, -3) # => 4

insert

  • str.insert(index, string ) → str

Inserts string before the character at the given index, modifying str. Negative indices count from the end of the string and insert after the given character. After the insertion, str will contain string starting at index.

"abcd".insert(0, 'X') # => "Xabcd"

"abcd".insert(3, 'X') # => "abcXd"

"abcd".insert(4, 'X') # => "abcdX"

"abcd".insert(-3, 'X') # => "abXcd"

"abcd".insert(-1, 'X') # => "abcdX"

intern

  • str.intern →symbol

Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. Can intern any string, not just identifiers. See Symbol#id2name.

"Koala".intern # => :Koala

sym = "$1.50 for a soda!?!?".intern

sym.to_s # => "$1.50 for a soda!?!?"

length

  • str.length →int

Returns the number of characters in str. See also String#bytesize.

lines

  • str.lines(sep=$/ ) → enum | array
  • str.lines(sep=$/ ) { |substr| … } → str}

Splits str using the supplied parameter as the record separator ($/ by default) and passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split into paragraphs, each terminated by multiple \n characters. With no block, returns a enumerator (Ruby 1.9) or an array (Ruby 2.0).«2.0»

print "Example one\n"

"hello\nworld".lines {|s| p s}

print "Example two\n"

"hello\nworld".lines('l') {|s| p s}

print "Example three\n"

"hello\n\n\nworld".lines('') {|s| p s}

Produces:

Example one

"hello\n"

"world"

Example two

"hel"

"l"

"o\nworl"

"d"

Example three

"hello\n\n\n"

"world"

ljust

  • str.ljust(width, padding=" " ) → string

If width is greater than the length of str, returns a new String of length width with str left justified and padded with copies of padding; otherwise, returns a copy of str.

"hello".ljust(4) # => "hello"

"hello".ljust(20) # => "hello␣␣␣␣␣␣␣␣␣␣␣␣␣␣

# .. "

"hello".ljust(20, "*") # => "hello***************"

"hello".ljust(20, " dolly") # => "hellodollydollydo"

lstrip

  • str.lstrip →string

Returns a copy of str with leading whitespace characters removed. Also see String#rstrip and String#strip.

" hello ".lstrip # => "hello␣␣"

"\000 hello ".lstrip # => "\0hello␣␣"

"hello".lstrip # => "hello"

lstrip!

  • str.lstrip! →str or nil

Removes leading whitespace characters from str, returning nil if no change was made. See also String#rstrip! and String#strip!.

" hello ".lstrip! # => "hello␣␣"

"hello".lstrip! # => nil

match

  • str.match(pattern ) → match_data or nil
  • str.match(pattern ) { |matchdata| … } → obj

Converts pattern to a Regexp (if it isn’t already one) and then invokes its match method on str. If a block is given, the block is passed the MatchData object, and the match method returns the value of the block.

'seed'.match('(.)\1') # => #<MatchData "ee" 1:"e">

'seed'.match('(.)\1')[0] # => "ee"

'seed'.match(/(.)\1/)[0] # => "ee"

'seed'.match('ll') # => nil

'seed'.match('ll') {|md| md[0].upcase } # => nil

'seed'.match('xx') # => nil

next

  • str.next →string

Synonym for String#succ.

next!

  • str.next! →str

Synonym for String#succ!.

oct

  • str.oct →int

Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number. Returns 0 if the conversion fails.

"123".oct # => 83

"-377".oct # => -255

"bad".oct # => 0

"0377bad".oct # => 255

ord

  • str.ord →int

Returns the integer code point of the first character of str.

# encoding: utf-8

"d".ord # => 100

"dog".ord # => 100

"∂".ord # => 8706

partition

  • str.partition(pattern ) → [ before, match, after ]

Searches str for pattern (which may be a string or a regular expression). Returns a three-element array containing the part of the string before the pattern, the part that matched the pattern, and the part after the match. If the pattern does not match, the entire string will be returned as the first element of the array, and the other two entries will be empty strings.

"THX1138".partition("11") # => ["THX", "11", "38"]

"THX1138".partition(/\d\d/) # => ["THX", "11", "38"]

"THX1138".partition("99") # => ["THX1138", "", ""]

prepend

  • str.prepend(other ) → str

Inserts other at the beginning of str.

str = "1138"

str.prepend("THX") # => "THX1138"

str # => "THX1138"

replace

  • str.replace(string ) → str

Replaces the contents, encoding, and taintedness of str with the corresponding values in string.

s = "hello" # => "hello"

s.replace "world" # => "world"

reverse

  • str.reverse →string

Returns a new string with the characters from str in reverse order.

# Every problem contains its own solution...

"stressed".reverse # => "desserts"

reverse!

  • str.reverse! →str

Reverses str in place.

rindex

  • str.rindex(string <, int> ) → int or nil
  • str.rindex(regexp <, int> ) → int or nil

Returns the index of the last occurrence of the given substring, character, or pattern in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to end the search—characters beyond this point will not be considered.

"hello".rindex('e') # => 1

"hello".rindex('l') # => 3

"hello".rindex('a') # => nil

"hello".rindex(/[aeiou]/, -2) # => 1

rjust

  • str.rjust(width, padding=" " ) → string

If width is greater than the length of str, returns a new String of length width with str right justified and padded with copies of padding; otherwise, returns a copy of str.

"hello".rjust(4) # => "hello"

"hello".rjust(20) # => "␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣h

# .. ello"

"hello".rjust(20, "-") # => "---------------hello"

"hello".rjust(20, "padding") # => "paddingpaddingphello"

rpartition

  • str.rpartition(pattern ) → [ before, match, after ]

Searches str for pattern (which may be a string or a regular expression), starting at the end of the string. Returns a three-element array containing the part of the string before the pattern, the part that matched the pattern, and the part after the match. If the pattern does not match, the entire string will be returned as the last element of the array, and the other two entries will be empty strings.

"THX1138".rpartition("1") # => ["THX1", "1", "38"]

"THX1138".rpartition(/1\d/) # => ["THX1", "13", "8"]

"THX1138".rpartition("99") # => ["", "", "THX1138"]

rstrip

  • str.rstrip →string

Returns a copy of str, stripping first trailing null characters and then stripping trailing whitespace characters. See also String#lstrip and String#strip.

" hello ".rstrip # => "␣␣hello"

" hello \000 ".rstrip # => "␣␣hello"

" hello \000".rstrip # => "␣␣hello"

"hello".rstrip # => "hello"

rstrip!

  • str.rstrip! →str or nil

Removes trailing null characters and then removes trailing whitespace characters from str. Returns nil if no change was made. See also String#lstrip! and #strip! .

" hello ".rstrip! # => "␣␣hello"

"hello".rstrip! # => nil

scan

  • str.scan(pattern ) → array
  • str.scan(pattern ) { |match, ...| … } → str}

Both forms iterate through str, matching the pattern (which may be a Regexp or a String). For each match, a result is generated and either added to the result array or passed to the block. If the pattern contains no groups, each individual result consists of the matched string, $&. If the pattern contains groups, each individual result is itself an array containing one entry per group. If the pattern is a String, it is interpreted literally (in other words, it is not taken to be a regular expression pattern).

a = "cruel world"

a.scan(/\w+/) # => ["cruel", "world"]

a.scan(/.../) # => ["cru", "el ", "wor"]

a.scan(/(...)/) # => [["cru"], ["el "], ["wor"]]

a.scan(/(..)(..)/) # => [["cr", "ue"], ["l ", "wo"]]

And the block form:

a.scan(/\w+/) {|w| print "<<#{w}>> " }

puts

a.scan(/(.)(.)/) {|a,b| print b, a }

puts

Produces:

<<cruel>> <<world>>

rceu lowlr

setbyte

  • str.setbyte(offset, byte ) → byte

Sets the byte at offset (starting from the end of the string if the offset is negative) to byte. Cannot be used to change the length of the string. Does not change the encoding of the string.

str = "defog"

# a utf-8 delta character

str.setbyte(0, 226) # => 226

str.setbyte(1, 136) # => 136

str.setbyte(2, 130) # => 130

str # => "∂og"

str.length # => 3

str.force_encoding("utf-8")

str.length # => 3

str # => "∂og"

size

  • str.size →int

Synonym for String#length.

slice

  • str.slice(int ) → string or nil
  • str.slice(int, int ) → string or nil
  • str.slice(range ) → string or nil
  • str.slice(regexp ) → string or nil
  • str.slice(match_string ) → string or nil

Synonym for String#[ ].

a = "hello there"

a.slice(1) # => "e"

a.slice(1,3) # => "ell"

a.slice(1..3) # => "ell"

a.slice(-3,2) # => "er"

a.slice(-4..-2) # => "her"

a.slice(-2..-4) # => ""

a.slice(/th[aeiou]/) # => "the"

a.slice("lo") # => "lo"

a.slice("bye") # => nil

slice!

  • str.slice!(int ) → string or nil
  • str.slice!(int, int ) → string or nil
  • str.slice!(range ) → string or nil
  • str.slice!(regexp ) → string or nil
  • str.slice!(match_string ) → string or nil

Deletes the specified portion from str and returns the portion deleted. The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently not change the string.

string = "this is a string"

string.slice!(2) # => "i"

string.slice!(3..6) # => " is "

string.slice!(/s.*t/) # => "sa st"

string.slice!("r") # => "r"

string # => "thing"

split

  • str.split(pattern=$;, <limit> ) → array

Divides str into substrings based on a delimiter, returning an array of these substrings.

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern includes groups, these groups will be included in the returned values.

If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if “␣” were specified.

If the limit parameter is omitted, trailing empty fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

" now's the time".split # => ["now's", "the", "time"]

" now's the time".split(' ') # => ["now's", "the", "time"]

" now's the time".split(/ /) # => ["", "now's", "", "", "the", "time"]

"a@1bb@2ccc".split(/@\d/) # => ["a", "bb", "ccc"]

"a@1bb@2ccc".split(/@(\d)/) # => ["a", "1", "bb", "2", "ccc"]

"1, 2.34,56, 7".split(/,\s*/) # => ["1", "2.34", "56", "7"]

"hello".split(//) # => ["h", "e", "l", "l", "o"]

"hello".split(//, 3) # => ["h", "e", "llo"]

"hi mom".split(/\s*/) # => ["h", "i", "m", "o", "m"]

"".split # => []

"mellow yellow".split("ello") # => ["m", "w y", "w"]

"1,2,,3,4,,".split(',') # => ["1", "2", "", "3", "4"]

"1,2,,3,4,,".split(',', 4) # => ["1", "2", "", "3,4,,"]

"1,2,,3,4,,".split(',', -4) # => ["1", "2", "", "3", "4", "", ""]

squeeze

  • str.squeeze(<string>* ) → squeezed_string

The parameter(s) specify a set of characters using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character.

"yellow moon".squeeze # => "yelow mon"

" now is the".squeeze(" ") # => " now is the"

"putters putt balls".squeeze("m-z") # => "puters put balls"

squeeze!

  • str.squeeze!(<string>* ) → str or nil

Squeezes str in place, returning str. Returns nil if no changes were made.

start_with?

  • str.start_with?(<prefix>+ ) → true or false

Returns true if str starts with any of the given prefixes.

"Apache".start_with?("Apa") # => true

"ruby code".start_with?("python", "perl", "ruby") # => true

strip

  • str.strip →string

Returns a new string, stripping leading whitespace and trailing null and whitespace characters from str.

" hello ".strip # => "hello"

"\tgoodbye\r\n".strip # => "goodbye"

"goodbye \000".strip # => "goodbye"

"goodbye \000 ".strip # => "goodbye"

strip!

  • str.strip! →str or nil

Removes leading whitespace and trailing null and whitespace characters from str. Returns nil if str was not altered.

sub

  • str.sub(pattern, replacement ) → string
  • str.sub(pattern ) { |match| … } → string

Returns a copy of str with the first occurrence of pattern replaced with either replacement or the value of the block. See the description of String#gsub for a description of the parameters.

"hello".sub(/[aeiou]/, '*') # => "h*llo"

"hello".sub(/([aeiou])/, '<\1>') # => "h<e>llo"

"hello".sub(/./) {|s| s[0].to_s + ' '} # => "h ello"

"hello".sub(/(?<double>l)/, '-\k<double>-') # => "he-l-lo"

sub!

  • str.sub!(pattern, replacement ) → str or nil
  • str.sub!(pattern ) { |match| … } → str or nil

Performs the substitutions of String#sub in place, returning str. Returns nil if no substitutions were performed.

succ

  • str.succ →string

Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set’s collating sequence.

If the increment generates a “carry,” the character to the left of it is incremented. This process repeats until there is no carry, adding a character if necessary. An exception is when the carry is generated by a sequence of digits in a string containing digits, nonalpha characters, and more digits, in which case the carry applies to the digits. This allows for incrementing (for example) numbers with decimal places.

"abcd".succ # => "abce"

"THX1138".succ # => "THX1139"

"<<koala>>".succ # => "<<koalb>>"

"1999zzz".succ # => "2000aaa"

"ZZZ9999".succ # => "AAAA0000"

"***".succ # => "**+"

"1.9".succ # => "2.0"

"1//9".succ # => "2//0"

"1/9/9/9".succ # => "2/0/0/0"

"1x9".succ # => "1y0"

succ!

  • str.succ! →str

Equivalent to String#succ but modifies the receiver in place.

sum

  • str.sum(n=16 ) → int

Returns a basic n-bit checksum of the characters in str, where n is the optional parameter, defaulting to 16. The result is simply the sum of the binary value of each character in str modulo 2n-1. This is not a particularly good checksum—see the digest libraries for better alternatives.

"now is the time".sum # => 1408

"now is the time".sum(8) # => 128

swapcase

  • str.swapcase →string

Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase. The mapping depends on the string encoding, but not all encodings produce expected results.

# encoding: utf-8

"Hello".swapcase # => "hELLO"

"cYbEr_PuNk11".swapcase # => "CyBeR_pUnK11"

"∂Og".swapcase # => "∂oG"

swapcase!

  • str.swapcase! →str or nil

Equivalent to String#swapcase but modifies str in place, returning str. Returns nil if no changes were made.

to_c

  • str.to_c →complex

Returns the result of interpreting leading characters in str as a complex number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, Complex(0,0) is returned. The method never raises an exception.

"123".to_c # => 123+0i

"4+5/6i".to_c # => 4+5/6i

"thx1138".to_c # => 0+0i

to_f

  • str.to_f →float

Returns the result of interpreting leading characters in str as a floating-point number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0.0 is returned. The method never raises an exception (use Object#Float to validate numbers).

"123.45e1".to_f # => 1234.5

"45.67 degrees".to_f # => 45.67

"thx1138".to_f # => 0.0

to_i

  • str.to_i(base=10 ) → int

Returns the result of interpreting leading characters in str as an integer base base (2 to 36). Given a base of zero, to_i looks for leading 0, 0b, 0o, 0d, or 0x and sets the base accordingly. Leading spaces are ignored, and leading plus or minus signs are honored. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. The method never raises an exception.

"12345".to_i # => 12345

"99 red balloons".to_i # => 99

"0a".to_i # => 0

"0a".to_i(16) # => 10

"0x10".to_i # => 0

"0x10".to_i(0) # => 16

"-0x10".to_i(0) # => -16

"hello".to_i(30) # => 14167554

"1100101".to_i(2) # => 101

"1100101".to_i(8) # => 294977

"1100101".to_i(10) # => 1100101

"1100101".to_i(16) # => 17826049

to_r

  • str.to_r →rational

Returns the result of interpreting leading characters in str as a rational number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, Rational(0,1) is returned. The method never raises an exception.

"123".to_r # => 123/1

"5/6".to_r # => 5/6

"5/six".to_r # => 5/1

"thx1138".to_r # => (0/1)

to_s

  • str.to_s →str

Returns the receiver.

to_str

  • str.to_str →str

Synonym for String#to_s. to_str is used by methods such as String#concat to convert their arguments to a string. Unlike to_s , which is supported by almost all classes, to_str is normally implemented only by those classes that act like strings. Of the built-in classes, only Exception and String implement to_str .

to_sym

  • str.to_s →symbol

Returns the symbol for str. This can create symbols that cannot be represented using the :xxx notation. A synonym for String#intern.

s = 'cat'.to_sym # => :cat

s == :cat # => true

'cat and dog'.to_sym # => :"cat and dog"

s == :'cat and dog' # => false

tr

  • str.tr(from_string, to_string ) → string

Returns a copy of str with the characters in from_string replaced by the corresponding characters in to_string. If to_string is shorter than from_string, it is padded with its last character. Both strings may use the c1–c2 notation to denote ranges of characters, and from_string may start with a ^, which denotes all characters except those listed.

"hello".tr('aeiou', '*') # => "h*ll*"

"hello".tr('^aeiou', '*') # => "*e**o"

"hello".tr('el', 'ip') # => "hippo"

"hello".tr('a-y', 'b-z') # => "ifmmp"

tr!

  • str.tr!(from_string, to_string ) → str or nil

Translates str in place, using the same rules as String#tr. Returns str or returns nil if no changes were made.

tr_s

  • str.tr_s(from_string, to_string ) → string

Processes a copy of str as described under String#tr and then removes duplicate characters in regions that were affected by the translation.

"hello".tr_s('l', 'r') # => "hero"

"hello".tr_s('el', '*') # => "h*o"

"hello".tr_s('el', 'hx') # => "hhxo"

tr_s!

  • str.tr_s!(from_string, to_string ) → str or nil

Performs String#tr_s processing on str in place, returning str. Returns nil if no changes were made.

unpack

  • str.unpack(format ) → array

Decodes str (which may contain binary data) according to the format string, returning an array of the extracted values. The format string consists of a sequence of single-character directives, summarized in Table 24, Directives for String#unpack. Each directive may be followed by a number, indicating the number of times to repeat this directive. An asterisk (*) will use up all remaining elements. The directives sSiIlL may each be followed by an underscore (_) or bang (!} to use the underlying platform’s native size for the specified type; otherwise, it uses a platform-independent consistent size. The directives s S i I l L q Q may be followed by a less than sign to signify little endian or greater than sign for big endian. Spaces are ignored in the format string. Comments starting with # to the next newline or end of string are also ignored. The encoding of the string is ignored; unpack treats the string as a sequence of bytes. See also Array#pack.

"abc \0\0abc \0\0".unpack('A6Z6') # => ["abc", "abc "]

"abc \0\0".unpack('a3a3') # => ["abc", " \0\0"]

"aa".unpack('b8B8') # => ["10000110", "01100001"]

"aaa".unpack('h2H2c') # => ["16", "61", 97]

"\xfe\xff\xfe\xff".unpack('sS') # => [-2, 65534]

"now=20is".unpack('M*') # => ["now is"]

"whole".unpack('xax2aX2aX1aX2a') # => ["h", "e", "l", "l", "o"]

upcase

  • str.upcase →string

Returns a copy of str with all lowercase letters replaced with their uppercase counterparts. The mapping depends on the string encoding, but not all encodings produce expected results.

# encoding: utf-8

"hEllO".upcase # => "HELLO"

"∂og".upcase # => "∂OG"

upcase!

  • str.upcase! →str or nil

Upcases the contents of str, returning nil if no changes were made.

upto

  • str.upto(string, exclude_end=false ) { |s| … } → str or enumerator

Iterates through successive values, starting at str and ending at string inclusive (or omitting string if the second parameter is true). Passes each value in turn to the block. The String#succ method is used to generate each value. Returns an Enumerator object if no block is given.

"a8".upto("b6") {|s| print s, ' ' }

puts

for s in "a8".."b6"

print s, ' '

end

Produces:

a8 a9 b0 b1 b2 b3 b4 b5 b6

a8 a9 b0 b1 b2 b3 b4 b5 b6

"a8".upto("b6", true).to_a # => ["a8", "a9", "b0", "b1", "b2", "b3", "b4", "b5"]

If the two strings contain just the digits 0 to 9, then successive numeric values (as strings) are generated. Leading zeros are handled appropriately.

"99".upto("103").to_a # => ["99", "100", "101", "102", "103"]

"00008".upto("00012").to_a # => ["00008", "00009", "00010", "00011", "00012"]

valid_encoding?

  • str.valid_encoding? → true or false

Returns true if str contains a valid byte sequence in its current encoding.

# encoding: binary

str = "\xE2"

str.force_encoding("utf-8")

str.valid_encoding? # => false

str = "\xE2\x88\x82"

str.force_encoding("utf-8")

str.valid_encoding? # => true

Table 24. Directives for String#unpack

Format

Function

Returns

A

Sequence of bytes with trailing nulls and ASCII spaces removed.

String

a

Sequence of bytes.

String

B

Extracts bits from each byte (MSB first).

String

b

Extracts bits from each byte (LSB first).

String

C

Extracts a byte as an unsigned integer.

Fixnum

c

Extracts a byte as an integer.

Fixnum

d,D

Treat sizeof(double) bytes as a native double.

Float

E

Treats sizeof(double) bytes as a double in little-endian byte order.

Float

e

Treats sizeof(float) bytes as a float in little-endian byte order.

Float

f,F

Treats sizeof(float) bytes as a native float.

Float

G

Treats sizeof(double) bytes as a double in network byte order.

Float

g

Treats sizeof(float) bytes as a float in network byte order.

Float

H

Extracts hex nibbles from each byte (most significant first).

String

h

Extracts hex nibbles from each byte (least significant first).

String

I

Treats sizeof(int)° successive bytes as an unsigned native integer.

Integer

i

Treats sizeof(int)° successive bytes as a signed native integer.

Integer

L

Treats four° successive bytes as an unsigned native long integer.

Integer

l

Treats four° successive characters as a signed native long integer.

Integer

M

Extracts a quoted-printable string.

String

m

Extracts a Base64-encoded string. By default, accepts \n and \r. "m0" rejects these.

String

N

Treats four bytes as an unsigned long in network byte order.

Fixnum

n

Treats two bytes as an unsigned short in network byte order.

Fixnum

P

Treats sizeof(char *) bytes as a pointer and returns len bytes from the referenced location.

String

p

Treats sizeof(char *) bytes as a pointer to a null-terminated string.

String

Q

Treats eight bytes as an unsigned quad word (64 bits).

Integer

q

Treats eight bytes as a signed quad word (64 bits).

Integer

S

Treats two° bytes characters as an unsigned short in native byte order.

Fixnum

s

Treats two° successive bytes as a signed short in native byte order.

Fixnum

U

Extracts UTF-8 characters as unsigned integers.

Integer

u

Extracts a UU-encoded string.

String

V

Treats four bytes as an unsigned long in little-endian byte order.

Fixnum

v

Treats two bytes as an unsigned short in little-endian byte order.

Fixnum

w

BER-compressed integer (see Array#pack for more information).

Integer

X

Skips backward one byte.

x

Skips forward one byte.

Z

String with trailing nulls removed.

String

@

Skips to the byte offset given by the length argument.

° May be modified by appending _ or ! to the directive.

Class Struct < Object

Subclasses are:

Struct::Tms

A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.

The Struct class is a generator of specific classes, each one of which is defined to hold a set of variables and their accessors. In these examples, we’ll call the generated class Customer, and we’ll show an example instance of that class as joe.

Also see OpenStruct.

In the descriptions that follow, the parameter symbol refers to a name, which is either a quoted string or a Symbol (such as :name).

Mixes in

Enumerable

all?, any?, chunk, collect, collect_concat, count, cycle, detect, drop, drop_while, each_cons, each_entry, each_slice, each_with_index, each_with_object, entries, find, find_all, find_index, first, flat_map, grep, group_by, include?, inject, lazy, map, max, max_by, member?, min, min_by, minmax, minmax_by, none?, one?, partition, reduce, reject, reverse_each, select, slice_before, sort, sort_by, take, take_while, to_a, zip

Struct: Class methods

new

  • Struct.new(<string> <, symbol>+ ) → Customer
  • Struct.new(<string> <, symbol>+ ) { … } → Customer

Creates a new class, named by string, containing accessor methods for the given symbols. If the name string is omitted, an anonymous structure class will be created. Otherwise, the name of this struct will appear as a constant in class Struct, so it must be unique for all Structs in the system and should start with a capital letter. Assigning a structure class to a constant effectively gives the class the name of the constant.

Struct.new returns a new Class object, which can then be used to create specific instances of the new structure. The remaining methods listed next (class and instance) are defined for this generated class. See the description that follows for an example.

# Create a structure with a name in Struct

Struct.new("Customer", :name, :address) # => Struct::Customer

Struct::Customer.new("Dave", "123 Main") # => #<struct Struct::Customer

# .. name="Dave", address="123 Main">

# Create a structure named by its constant

Customer = Struct.new(:name, :address) # => Customer

Customer.new("Dave", "123 Main") # => #<struct Customer name="Dave",

# .. address="123 Main">

A block passed to the constructor is evaluated in the context of the new struct’s class and hence allows you conveniently to add instance methods to the new struct.

Customer = Struct.new(:name, :address) do

def to_s

"#{self.name} lives at #{self.address}"

end

end

Customer.new("Dave", "123 Main").to_s # => "Dave lives at 123 Main"

new

  • Customer.new(<obj>+ ) → joe

Creates a new instance of a structure (the class created by Struct.new). The number of actual parameters must be less than or equal to the number of attributes defined for this class; unset parameters default to nil. Passing too many parameters will raise an ArgumentError.

Customer = Struct.new(:name, :address, :zip)

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe.name # => "Joe Smith"

joe.zip # => 12345

[ ]

  • Customer[<obj>+ ] → joe

Synonym for new (for the generated structure).

Customer = Struct.new(:name, :address, :zip)

joe = Customer["Joe Smith", "123 Maple, Anytown NC", 12345]

joe.name # => "Joe Smith"

joe.zip # => 12345

members

  • Customer.members →array

Returns an array of symbols representing the names of the instance variables.

Customer = Struct.new("Customer", :name, :address, :zip)

Customer.members # => [:name, :address, :zip]

Struct: Instance methods

==

  • joe== other_structtrue or false

Equality—Returns true if other_struct is equal to this one: they must be of the same class as generated by Struct.new, and the values of all instance variables must be equal (according to Object#==).

Customer = Struct.new(:name, :address, :zip)

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joejr = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

jane = Customer.new("Jane Doe", "456 Elm, Anytown NC", 12345)

joe == joejr # => true

joe == jane # => false

[ ]

  • joe[symbol ] → obj
  • joe[integer ] → obj

Attribute Reference—Returns the value of the instance variable named by symbol or indexed (0..length-1) by int. Raises NameError if the named variable does not exist or raises IndexError if the index is out of range.

Customer = Struct.new(:name, :address, :zip)

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe["name"] # => "Joe Smith"

joe[:name] # => "Joe Smith"

joe[0] # => "Joe Smith"

[ ]=

  • joe[symbol ] = objobj
  • joe[int ] = objobj

Attribute Assignment—Assigns to the instance variable named by symbol or int the value obj and returns it. Raises a NameError if the named variable does not exist or raises an IndexError if the index is out of range.

Customer = Struct.new(:name, :address, :zip)

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe["name"] = "Luke"

joe[:zip] = "90210"

joe.name # => "Luke"

joe.zip # => "90210"

each

  • joe.each { |obj| … } →joe

Calls block once for each instance variable, passing the value as a parameter.

Customer = Struct.new(:name, :address, :zip)

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe.each {|x| puts(x) }

Produces:

Joe Smith

123 Maple, Anytown NC

12345

each_pair

  • joe.each_pair { |symbol, obj| … } →joe

Calls block once for each instance variable, passing the name (as a symbol) and the value as parameters.

Customer = Struct.new(:name, :address, :zip)

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe.each_pair {|name, value| puts("#{name} => #{value}") }

Produces:

name => Joe Smith

address => 123 Maple, Anytown NC

zip => 12345

length

  • joe.length →int

Returns the number of attributes.

Customer = Struct.new(:name, :address, :zip)

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe.length # => 3

members

  • joe.members →array

Returns the names of the instance variables as an array of symbols.

Customer = Struct.new(:name, :address, :zip)

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe.members # => [:name, :address, :zip]

size

  • joe.size →int

Synonym for Struct#length.

to_a

  • joe.to_a →array

Returns the values for this instance as an array.

Customer = Struct.new(:name, :address, :zip)

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe.to_a[1] # => "123 Maple, Anytown NC"

to_h

  • joe.to_h →hash

Returns a hash of key/values pairs in this struct.

Customer = Struct.new(:name, :address, :zip)

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)

joe.to_h # => {:name=>"Joe Smith", :address=>"123 Maple, Anytown NC",

# .. :zip=>12345}

values

  • joe.values →array

Synonym for to_a .

values_at

  • joe.values_at(<selector>* ) → array

Returns an array containing the elements in joe corresponding to the given indices. The selectors may be integer indices or ranges.

Lots = Struct.new(:a, :b, :c, :d, :e, :f)

l = Lots.new(11, 22, 33, 44, 55, 66)

l.values_at(1, 3, 5) # => [22, 44, 66]

l.values_at(0, 2, 4) # => [11, 33, 55]

l.values_at(-1, -3, -5) # => [66, 44, 22]

Class Struct::Tms < Struct

This structure is returned by Process.times. It holds information on process times on those platforms that support it. Not all values are valid on all platforms. This structure contains the following instance variables and the corresponding accessors:

utime

Amount of user CPU time, in seconds

stime

Amount of system CPU time, in seconds

cutime

Total of completed child processes’ user CPU time, in seconds (always 0 on Windows)

cstime

Total of completed child processes’ system CPU time, in seconds (always 0 on Windows)

See also Struct and Process.times.

def eat_cpu

10_000.times { File.open("/etc/passwd").close }

end

3.times { fork { eat_cpu } }

eat_cpu

Process.waitall

t = Process::times

[ t.utime, t.stime] # => [0.13, 0.24]

[ t.cutime, t.cstime ] # => [0.27, 0.68]

Class Symbol < Object

Symbol objects represent names inside the Ruby interpreter. They are generated using the :name or :"arbitrary text" literal syntax and by using the various to_sym methods. The same Symbol object will be created for a given name string for the duration of a program’s execution, regardless of the context or meaning of that name. Symbols can be arbitrary sequences of characters. Like strings, a symbol literal containing any characters with the top bit set will have an encoding determined by the encoding of the source file containing the definition.

Ruby 1.9 added string-like functionality to symbols.

Mixes in

Comparable

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

Symbol: Class methods

all_symbols

  • Symbol.all_symbols →array

Returns an array of all the symbols currently in Ruby’s symbol table.

list = Symbol.all_symbols

list.size # => 2240

list.grep(/attr_/) # => [:attr_reader, :attr_writer, :attr_accessor, :attr_name]

Symbol: Instance methods

<=>

  • sym<=> other_sym → -1, 0, +1, or nil

Compares sym to other_sym after converting each to strings. <=> is the basis for the methods < , <= , > , >= , and between? , included from module Comparable. The method Symbol#== does not use Comparable#==.

:abcdef <=> :abcde # => 1

:abcdef <=> :abcdef # => 0

:abcdef <=> :abcdefg # => -1

:abcdef <=> :ABCDEF # => 1

==

  • sym== objtrue or false

Returns true only if sym and obj are symbols with the same object_id .

:abcdef == :abcde # => false

:abcdef == :abcdef # => true

=~

  • sym=~ objint or nil

Converts sym to a string and matches it against obj.

:abcdef =~ /.[aeiou]/ # => 3

:abcdef =~ /xx/ # => nil

[ ]

  • sym[int ] → string or nil
  • sym[int, int ] → string or nil
  • sym[range ] → string or nil
  • sym[regexp ] → string or nil
  • sym[regexp, int ] → string or nil
  • sym[string ] → string or nil

Converts sym to a string and then indexes it using the same parameters as String#[].

:"hello there"[1] # => "e"

:"hello there"[1,3] # => "ell"

:"hello there"[1..3] # => "ell"

:"hello there"[-3,2] # => "er"

:"hello there"[-4..-2] # => "her"

:"hello there"[-2..-4] # => ""

:"hello there"[/[aeiou](.)\1/] # => "ell"

:"hello there"[/[aeiou](.)\1/, 1] # => "l"

capitalize

  • sym.capitalize →symbol

Returns a symbol with the first character of sym converted to uppercase and the remainder to lowercase.

:hello.capitalize # => :Hello

:"HELLO WORLD".capitalize # => :"Hello world"

:"123ABC".capitalize # => :"123abc"

casecmp

  • sym.casecmp(other ) → -1, 0, +1, or nil

Case-insensitive version of Symbol#<=>. Returns nil if other is not a symbol.

:abcdef.casecmp(:abcde) # => 1

:abcdef.casecmp(:abcdef) # => 0

:abcdef.casecmp(:ABCDEF) # => 0

:aBcDeF.casecmp(:abcdef) # => 0

:abcdef.casecmp(:abcdefg) # => -1

:abcdef.casecmp("abcdef") # => nil

downcase

  • sym.downcase →symbol

Returns a symbol with all the characters of sym converted to lowercase.

:Hello.downcase # => :hello

:"HELLO WORLD".downcase # => :"hello world"

:"123ABC".downcase # => :"123abc"

empty?

  • sym.empty → true or false

Returns true if the string representation of sym is empty.

:hello.empty? # => false

:"".empty? # => true

encoding

  • sym.encoding →enc

Returns the encoding of sym.

# encoding: utf-8

:hello.encoding # => #<Encoding:US-ASCII>

:"∂og".encoding # => #<Encoding:UTF-8>

id2name

  • sym.id2name →string

Returns the string representation of sym.

:fred.id2name # => "fred"

:"99 red balloons!".id2name # => "99 red balloons!"

inspect

  • sym.inspect →string

Returns the representation of sym as a symbol literal.

:fred.inspect # => :fred

:"99 red balloons!".inspect # => :"99 red balloons!"

intern

  • sym.intern →sym

Synonym for Symbol#to_sym.

length

  • sym.length →int

Returns the number of characters in the string representation sym.

# encoding: utf-8

:dog.length # => 3

:∂og.length # => 3

match

  • sym.match(regexp ) → int or nil

Converts self to a string and then matches it against regexp. Unlike String#match, does not support blocks or non-regexp parameters.

:hello.match(/(.)\1/) # => 2

:hello.match(/ll/) # => 2

next

  • sym.next →symbol

Synonym for Symbol#succ.

size

  • sym.size →int

Synonym for Symbol#length.

slice

  • sym.slice(int ) → string or nil
  • sym.slice(int, int ) → string or nil
  • sym.slice(range ) → string or nil
  • sym.slice(regexp ) → string or nil
  • sym.slice(match_string ) → string or nil

Synonym for Symbol#[ ].

succ

  • sym.succ →symbol

Returns the successor to sym using the same rules as String#succ.

:abcd.succ # => :abce

:THX1138.succ # => :THX1139

:"1999zzz".succ # => :"2000aaa"

swapcase

  • sym.swapcase →symbol

Returns a symbol with the case of all the characters of sym swapped.

:Hello.swapcase # => :hELLO

:"123ABC".swapcase # => :"123abc"

to_proc

  • sym.to_proc →proc

Allows a symbol to be used when a block is expected. The symbol acts as a method invoked on each parameter to the block. See The Symbol.to_proc Trick for more information.

%w{ant bee cat}.map(&:reverse) # => ["tna", "eeb", "tac"]

to_s

  • sym.to_s →string

Synonym for Symbol#id2name.

to_sym

  • sym.to_sym →sym

Symbols are symbol-like!

upcase

  • sym.upcase →symbol

Returns a symbol with all the characters of sym in uppercase.

:Hello.upcase # => :HELLO

:"123Abc".upcase # => :"123ABC"

Class Thread < Object

Thread encapsulates the behavior of a thread of execution, including the main thread of the Ruby script. See the tutorial beginning Chapter 12, Fibers, Threads, and Processes.

In the descriptions that follow, the parameter symbol refers to a name that is either a quoted string or a symbol (such as :name).

Thread: Class methods

abort_on_exception

  • Thread.abort_on_exception → true or false

Returns the status of the global abort on exception condition. The default is false. When set to true or if the global $DEBUG flag is true (perhaps because the command-line option -d was specified), all threads will abort (the process will exit(0)) if an exception is raised in any thread. See alsoThread.abort_on_exception=.

abort_on_exception=

  • Thread.abort_on_exception= true or falsetrue or false

When set to true, all threads will abort if an exception is raised. Returns the new state.

Thread.abort_on_exception = true

t1 = Thread.new do

puts "In new thread"

raise "Exception from thread"

end

sleep(0.1)

puts "not reached"

Produces:

In new thread

prog.rb:4:in `block in <main>': Exception from thread (RuntimeError)

current

  • Thread.current →thread

Returns the currently executing thread.

Thread.current # => #<Thread:0x007fb2340c0ce0 run>

exclusive

  • Thread.exclusive { … } →obj

Executes the block and returns whatever the block returns. Internally uses a Mutex so that only one thread can be executing code under the control of Thread.exclusive at a time.

exit

  • Thread.exit

Terminates the currently running thread and schedules another thread to be run. If this thread is already marked to be killed, exit returns the Thread. If this is the main thread, or the last thread, exits the process.

fork

  • Thread.fork { &hel