Ruby Language Reference


Reserved Words:

The following list shows the reserved words in Ruby. These reserved words may not be used as constant or variable names. They can, however, be used as method names.

ENDelsenilltrue
aliaselsifnotundef
andendorunless
beginensureredountil
breakfalserescuewhen
caseforretrywhile
classifreturnwhile
definself__FILE__
defined?modulesuper__LINE__

 

Escape Characters:

Following table is a list of escape or non-printable characters that can be represented with backslash notation.

NOTE: In a doublequoted string, an escape character is interpreted; in a singlequoted string, an escape character is preserved.

Backslash
notation
Hexadecimal
character
Description
\a0x07Bell or alert
\b0x08Backspace
\cx Control-x
\C-x Control-x
\e0x1bEscape
\f0x0cFormfeed
\M-\C-x Meta-Control-x
\n0x0aNewline
\nnn Octal notation, where n is in the range 0.7
\r0x0dCarriage return
\s0x20Space
\t0x09Tab
\v0x0bVertical tab
\x Character x
\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

 

Character Encoding:

Following are the Character Encoding Characters:

Code Description
aASCII (same as none). This is the default.
eEUC.
nNone (same as ASCII).
uUTF-8.

 

String Built-in Methods:

Following are the public String methods ( Assuming str is a String object ):

SN Methods with Description
1str % arg
Formats a string using a format specification. arg must be an array if it contains more than one substitution. For information on the format specification. see sprintf under "Kernel Module."
2str * integer
Returns a new string containing integer times str. In other words, str is repeated integer imes.
3str + other_str
Concatenates other_str to str.
4str << obj
Concatenates an object to str. If the object is a Fixnum in the range 0.255, it is converted to a character. Compare it with concat.
5str <=> other_str
Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is casesensitive.
6str == obj
Tests str and obj for equality. If obj is not a String, returns false; returns true if str <=> obj returns 0.
7str =~ obj
Matches str against a regular expression pattern obj. Returns the position where the match starts; otherwise, false.
8str =~ obj
Matches str against a regular expression pattern obj. Returns the position where the match starts; otherwise, false.
9str.capitalize
Capitalizes a string.
10str.capitalize!
Same as capitalize, but changes are made in place.
11str.casecmp
Makes a case-insensitive comparison of strings.
12str.center
Centers a string.
13str.chomp
Removes the record separator ($/), usually \n, from the end of a string. If no record separator exists, does nothing.
14str.chomp!
Same as chomp, but changes are made in place.
15str.chop
Removes the last character in str.
16str.chop!
Same as chop, but changes are made in place.
17str.concat(other_str)
Concatenates other_str to str.
18str.count(str, ...)
Counts one or more sets of characters. If there is more than one set of characters, counts the intersection of those sets
19str.crypt(other_str)
Applies a one-way cryptographic hash to str. The argument is the salt string, which should be two characters long, each character in the range a.z, A.Z, 0.9, . or /.
20str.delete(other_str, ...)
Returns a copy of str with all characters in the intersection of its arguments deleted.
21str.delete!(other_str, ...)
Same as delete, but changes are made in place.
22str.downcase
Returns a copy of str with all uppercase letters replaced with lowercase.
23str.downcase!
Same as downcase, but changes are made in place.
24str.dump
Returns a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped.
25str.each(separator=$/) { |substr| block }
Splits str using argument as the record separator ($/ by default), passing each substring to the supplied block.
26str.each_byte { |fixnum| block }
Passes each byte from str to the block, returning each byte as a decimal representation of the byte.
27str.each_line(separator=$/) { |substr| block }
Splits str using argument as the record separator ($/ by default), passing each substring to the supplied block.
28str.empty?
Returns true if str is empty (has a zero length).
29str.eql?(other)
Two strings are equal if the have the same length and content.
30str.gsub(pattern, replacement) [or]
str.gsub(pattern) { |match| block }

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')
31str[fixnum] [or] str[fixnum,fixnum] [or] str[range] [or] str[regexp] [or] str[regexp, fixnum] [or] str[other_str]
References str, using the following arguments: one Fixnum, returns a character code at fixnum; two Fixnums, returns a substring starting at an offset (first fixnum) to length (second fixnum); range, returns a substring in the range; regexp returns portion of matched string; regexp with fixnum, returns matched data at fixnum; other_str returns substring matching other_str. A negative Fixnum starts at end of string with -1.
32str[fixnum] = fixnum [or] str[fixnum] = new_str [or] str[fixnum, fixnum] = new_str [or] str[range] = aString [or] str[regexp] =new_str [or] str[regexp, fixnum] =new_str [or] str[other_str] = new_str ]
Replace (assign) all or part of a string. Synonym of slice!.
33str.gsub!(pattern, replacement) [or] str.gsub!(pattern) { |match| block }
Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed.
34str.hash
Returns a hash based on the string's length and content.
35str.hex
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.
36str.include? other_str [or] str.include? fixnum
Returns true if str contains the given string or character.
37str.index(substring [, offset]) [or]
str.index(fixnum [, offset]) [or]
str.index(regexp [, offset])

Returns the index of the first occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.
38str.insert(index, other_str)
Inserts other_str before the character at the given index, modifying str. Negative indices count from the end of the string, and insert after the given character. The intent is to insert a string so that it starts at the given index.
39str.inspect
Returns a printable version of str, with special characters escaped.
40str.intern [or] str.to_sym
Returns the Symbol corresponding to str, creating the symbol if it did not previously exist.
41str.length
Returns the length of str. Compare size.
42str.ljust(integer, padstr=' ')
If integer is greater than the length of str, returns a new String of length integer with str left-justified and padded with padstr; otherwise, returns str.
43str.lstrip
Returns a copy of str with leading whitespace removed.
44str.lstrip!
Removes leading whitespace from str, returning nil if no change was made.
45str.match(pattern)
Converts pattern to a Regexp (if it isn't already one), then invokes its match method on str.
46str.oct
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.
47str.replace(other_str)
Replaces the contents and taintedness of str with the corresponding values in other_str.
48str.reverse
Returns a new string with the characters from str in reverse order.
49str.reverse!
Reverses str in place.
50str.rindex(substring [, fixnum]) [or]
str.rindex(fixnum [, fixnum]) [or]
str.rindex(regexp [, fixnum])

Returns the index of the last occurrence of the given substring, character (fixnum), or pattern (regexp) 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 won't be considered.
51str.rjust(integer, padstr=' ')
If integer is greater than the length of str, returns a new String of length integer with str right-justified and padded with padstr; otherwise, returns str.
52str.rstrip
Returns a copy of str with trailing whitespace removed.
53str.rstrip!
Removes trailing whitespace from str, returning nil if no change was made.
54str.scan(pattern) [or]
str.scan(pattern) { |match, ...| block }

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.
55str.slice(fixnum) [or] str.slice(fixnum, fixnum) [or]
str.slice(range) [or] str.slice(regexp) [or]
str.slice(regexp, fixnum) [or] str.slice(other_str)
See str[fixnum], etc.
str.slice!(fixnum) [or] str.slice!(fixnum, fixnum) [or] str.slice!(range) [or] str.slice!(regexp) [or] str.slice!(other_str)

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 ignore the assignment.
56str.split(pattern=$;, [limit])
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 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 null 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.
57str.squeeze([other_str]*)
Builds a set of characters from the other_str parameter(s) 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.
58str.squeeze!([other_str]*)
Squeezes str in place, returning either str, or nil if no changes were made.
59str.strip
Returns a copy of str with leading and trailing whitespace removed.
60str.strip!
Removes leading and trailing whitespace from str. Returns nil if str was not altered.
61str.sub(pattern, replacement) [or]
str.sub(pattern) { |match| block }

Returns a copy of str with the first occurrence 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.
62str.sub!(pattern, replacement) [or]
str.sub!(pattern) { |match| block }

Performs the substitutions of String#sub in place, returning str, or nil if no substitutions were performed.
63str.succ [or] str.next
Returns the successor to str.
64str.succ! [or] str.next!
Equivalent to String#succ, but modifies the receiver in place.
65str.sum(n=16)
Returns a basic n-bit checksum of the characters in str, where n is the optional Fixnum 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.
66str.swapcase
Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase.
67str.swapcase!
Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made.
68str.to_f
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. This method never raises an exception.
69str.to_i(base=10)
Returns the result of interpreting leading characters in str as an integer base (base 2, 8, 10, or 16). 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. This method never raises an exception.
70str.to_s [or] str.to_str
Returns the receiver.
71str.tr(from_str, to_str)
Returns a copy of str with the characters in from_str replaced by the corresponding characters in to_str. If to_str is shorter than from_str, it is padded with its last character. Both strings may use the c1.c2 notation to denote ranges of characters, and from_str may start with a ^, which denotes all characters except those listed.
72str.tr!(from_str, to_str)
Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made.
73str.tr_s(from_str, to_str)
Processes a copy of str as described under String#tr, then removes duplicate characters in regions that were affected by the translation.
74str.tr_s!(from_str, to_str)
Performs String#tr_s processing on str in place, returning str, or nil if no changes were made.
75str.unpack(format)
Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted. The format string consists of a sequence of single-character directives, summarized in Table 18. Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk (*) will use up all remaining elements. The directives sSiIlL may each be followed by an underscore (_) to use the underlying platform's native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the format string.
76str.upcase
Returns a copy of str with all lowercase letters replaced with their uppercase counterparts. The operation is locale insensitive.only characters a to z are affected.
77str.upcase!
Changes the contents of str to uppercase, returning nil if no changes are made.
78str.upto(other_str) { |s| block }
Iterates through successive values, starting at str and ending at other_str inclusive, passing each value in turn to the block. The String#succ method is used to generate each value.

 

String unpack directives:

Following table lists unpack directives for method String#unpack.

Directive Returns Description
AStringWith trailing nulls and spaces removed.
aStringString.
BStringExtract bits from each character (most significant bit first).
bStringExtract bits from each character (least significant bit first).
CFixnumExtract a character as an unsigned integer.
cFixnumExtract a character as an integer.
D, dFloatTreat sizeof(double) characters as a native double.
EFloatTreat sizeof(double) characters as a double in littleendian byte order.
eFloatTreat sizeof(float) characters as a float in littleendian byte order.
F, fFloatTreat sizeof(float) characters as a native float.
GFloatTreat sizeof(double) characters as a double in network byte order.
gStringTreat sizeof(float) characters as a float in network byte order.
HStringExtract hex nibbles from each character (most significant bit first)
hStringExtract hex nibbles from each character (least significant bit first).
IIntegerTreat sizeof(int) (modified by _) successive characters as an unsigned native integer.
iIntegerTreat sizeof(int) (modified by _) successive characters as a signed native integer.
LIntegerTreat four (modified by _) successive characters as an unsigned native long integer.
lIntegerTreat four (modified by _) successive characters as a signed native long integer.
MStringQuoted-printable.
mStringBase64-encoded.
NIntegerTreat four characters as an unsigned long in network byte order.
nFixnumTreat two characters as an unsigned short in network byte order.
PStringTreat sizeof(char *) characters as a pointer, and return \emph{len} characters from the referenced location.
pStringTreat sizeof(char *) characters as a pointer to a nullterminated string.
QIntegerTreat eight characters as an unsigned quad word (64 bits).
qIntegerTreat eight characters as a signed quad word (64 bits).
SFixnumTreat two (different if _ used) successive characters as an unsigned short in native byte order.
sFixnumTreat two (different if _ used) successive characters as a signed short in native byte order.
UIntegerUTF-8 characters as unsigned integers.
uStringUU-encoded.
VFixnumTreat four characters as an unsigned long in little-endian byte order.
vFixnumTreat two characters as an unsigned short in little-endian byte order.
wIntegerBER-compressed integer.
X Skip backward one character.
x Skip forward one character.
ZStringWith trailing nulls removed up to first null with *.
@ Skip to the offset given by the length argument.

 

Ruby Arithmetic Operators:

Assume variable a holds 10 and variable b holds 20 then:

Operator Description Example
+Addition - Adds values on either side of the operator a + b will give 30
-Subtraction - Subtracts right hand operand from left hand operand a - b will give -10
*Multiplication - Multiplies values on either side of the operator a * b will give 200
/Division - Divides left hand operand by right hand operand b / a will give 2
%Modulus - Divides left hand operand by right hand operand and returns remainder b % a will give 0
**Exponent - Performs exponential (power) calculation on operators a**b will give 10 to the power 20

 

Ruby Comparison Operators:

Assume variable a holds 10 and variable b holds 20 then:

Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (a == b) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a <= b) is true.
<=> Combined comparison operator. Returns 0 if first operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second. (a <=> b) returns -1.
=== Used to test equality within a when clause of a case statement. (1...10) === 5 returns true.
.eql?True if the receiver and argument have both the same type and equal values. 1 == 1.0 returns true, but 1.eql?(1.0) is false.
equal?True if the receiver and argument have the same object id. 1 == 1.0 returns true, but 1.eql?(1.0) is false.

 

Ruby Assignment Operators:

Assume variable a holds 10 and variable b holds 20 then:

Operator Description Example
=Simple assignment operator, Assigns values from right side operands to left side operand c = a + b will assigne value of a + b into c
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
**=Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a

 

There are following Bitwise operators supported by Ruby language

Assume if a = 60; and b = 13; Now in binary format they will be as follows:

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. (a & b) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in eather operand. (a | b) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (a ^ b) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. (~a ) will give -61 which is 0011 1101
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. a << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. a >> 2 will give 15 which is 0000 1111

 

Ruby Logical Operators:

There are following logical operators supported by Ruby language

Assume variable a holds 10 and variable b holds 20 then:

Operator Description Example
and Called Logical AND operator. If both the operands are true then then condition becomes true. (a and b) is true.
orCalled Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (a or b) is true.
&& Called Logical AND operator. If both the operands are non zero then then condition becomes true. (a && b) is true.
||Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (a || b) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(a && b) is false.
notCalled Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. not(a && b) is false.

 

Ruby Ternary operator:

There is one more operator called Ternary Operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditioanl operator has this syntax:

Operator Description Example
? :Conditional Expression If Condition is true ? Then value X : Otherwise value Y

 

Ruby Range operators:

Sequence ranges in Ruby are used to create a range of successive values - consisting of a start value, an end value and a range of values in between.

In Ruby, these sequences are created using the ".." and "..." range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.

Operator Description Example
..Creates a range from start point to end point inclusive 1..10 Creates a range from 1 to 10 inclusive
...Creates a range from start point to end point exclusive 1...10 Creates a range from 1 to 9

 

Ruby Operators Precedence

The following table lists all operators from highest precedence to lowest.

Method Operator Description
Yes :: Constant resolution operator
Yes [ ] [ ]= Element reference, element set
Yes ** Exponentiation (raise to the power)
Yes ! ~ + - Not, complement, unary plus and minus (method names for the last two are +@ and -@)
Yes * / % Multiply, divide, and modulo
Yes + - Addition and subtraction
Yes >> << Right and left bitwise shift
Yes & Bitwise 'AND'
Yes ^ | Bitwise exclusive `OR' and regular `OR'
Yes <= < > >= Comparison operators
Yes <=> == === != =~ !~ Equality and pattern match operators (!= and !~ may not be defined as methods)
&& Logical 'AND'
|| Logical 'AND'
.. ... Range (inclusive and exclusive)
? : Ternary if-then-else
= %= /= -= += |= &= >>= <<= *= &&= ||= **= Assignment
defined? Check if specified symbol defined
not Logical negation
or and Logical composition

NOTE: Operators with a Yes in the method column are actually methods, and as such may be overridden.

 

Ruby public array methods

Following are the public array methods ( Assuming array is an array object ):

SN Methods with Description
1array & other_array
Returns a new array containing elements common to the two arrays, with no duplicates.
2array * int [or] array * str
Returns a new array built by concatenating the int copies of self. With a String argument, equivalent to self.join(str).
3array + other_array
Returns a new array built by concatenating the two arrays together to produce a third array.
4array . other_array
Returns a new array that is a copy of the original array, removing any items that also appear in other_array.
5str <=> other_str
Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is casesensitive.
6array | other_array
Returns a new array by joining array with other_array, removing duplicates.
7array << obj
Pushes the given object onto the end of array. This expression returns the array itself, so several appends may be chained together.
8array <=> other_array
Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than other_array.
9array == other_array
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.
10array[index] [or] array[start, length] [or]
array[range] [or] array.slice(index) [or]
array.slice(start, length) [or] array.slice(range)

Returns the element at index, or returns a subarray starting at start and continuing for length elements, 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 (or starting index) is out of range.
11array[index] = obj [or]
array[start, length] = obj or an_array or nil [or]
array[range] = obj or an_array or nil

Sets the element at index, or replaces a subarray starting at start and continuing for length elements, or replaces a subarray specified by range. If indices are greater than the current capacity of the array, the array grows automatically. Negative indices will count backward from the end of the array. Inserts elements if length is zero. If nil is used in the second and third form, deletes elements from self.
12array.abbrev(pattern = nil)
Calculates the set of unambiguous abbreviations for the strings in self. If passed a pattern or a string, only the strings matching the pattern or starting with the string are considered.
13array.assoc(obj)
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 , or nil if no match is found.
14array.at(index)
Returns the element at index. A negative index counts from the end of self. Returns nil if the index is out of range.
15array.clear
Removes all elements from array.
16array.collect { |item| block } [or]
array.map { |item| block }

Invokes block once for each element of self. Creates a new array containing the values returned by the block.
17array.collect! { |item| block } [or]
array.map! { |item| block }

Invokes block once for each element of self, replacing the element with the value returned by block.
18array.compact
Returns a copy of self with all nil elements removed.
19array.compact!
Removes nil elements from array. Returns nil if no changes were made.
20array.concat(other_array)
Appends the elements in other_array to self.
21array.delete(obj) [or]
array.delete(obj) { block }

Deletes items from self 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.
22array.delete_at(index)
Deletes the element at the specified index, returning that element, or nil if the index is out of range.
23array.delete_if { |item| block }
Deletes every element of self for which block evaluates to true.
24array.each { |item| block }
Calls block once for each element in self, passing that element as a parameter.
25array.each_index { |index| block }
Same as Array#each, but passes the index of the element instead of the element itself.
26array.empty?
Returns true if the self array contains no elements.
27array.eql?(other)
Returns true if array and other are the same object, or are both arrays with the same content.
28array.fetch(index) [or]
array.fetch(index, default) [or]
array.fetch(index) { |index| block }

Tries to return the element at position index. If 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 block, passing in index. Negative values of index count from the end of the array.
29array.fill(obj) [or]
array.fill(obj, start [, length]) [or]
array.fill(obj, range) [or]
array.fill { |index| block } [or]
array.fill(start [, length] ) { |index| block } [or]
array.fill(range) { |index| block }

The first three forms set the selected elements of self to obj. A start of nil is equivalent to zero. A length of nil is equivalent to self.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.
30array.first [or]
array.first(n)

Returns the first element, or the first n elements, of the array. If the array is empty, the first form returns nil, and the second form returns an empty array.
31array.flatten
Returns a new array that is a one-dimensional flattening of this array (recursively).
32array.flatten!
Flattens array in place. Returns nil if no modifications were made. (array contains no subarrays.)
33array.frozen?
Returns true if array is frozen (or temporarily frozen while being sorted).
34array.hash
Compute a hash-code for array. Two arrays with the same content will have the same hash code
35array.include?(obj)
Returns true if obj is present in self, false otherwise.
36array.index(obj)
Returns the index of the first object in self that is == to obj. Returns nil if no match is found.
37array.indexes(i1, i2, ... iN) [or]
array.indices(i1, i2, ... iN)

This methods is deprecated in latest version of Ruby so please use Array#values_at.
38array.indices(i1, i2, ... iN) [or]
array.indexes(i1, i2, ... iN)

This methods is deprecated in latest version of Ruby so please use Array#values_at.
39array.insert(index, obj...)
Inserts the given values before the element with the given index (which may be negative).
40array.inspect
Creates a printable version of array.
41array.join(sep=$,)
Returns a string created by converting each element of the array to a string, separated by sep.
42array.last [or] array.last(n)
Returns the last element(s) of self. If array is empty, the first form returns nil.
43array.length
Returns the number of elements in self. May be zero.
44array.map { |item| block } [or]
array.collect { |item| block }

Invokes block once for each element of self. Creates a new array containing the values returned by the block.
45array.map! { |item| block } [or]
array.collect! { |item| block }

Invokes block once for each element of array, replacing the element with the value returned by block.
46array.nitems
Returns the number of non-nil elements in self. May be zero.
47array.pack(aTemplateString)
Packs the contents of array into a binary sequence according to the directives in aTemplateString. 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. Any of the directives sSiIlL may be followed by an underscore (_) to use the underlying platform's native size for the specified type; otherwise, they use a platformindependent size. Spaces are ignored in the template string. ( See templating Table below )
48array.pop
Removes the last element from array and returns it, or nil if array is empty.
49array.push(obj, ...)
Pushes (appends) the given obj onto the end of this array. This expression returns the array itself, so several appends may be chained together.
50array.rassoc(key)
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.
51array.reject { |item| block }
Returns a new array containing the items array for which the block is not true.
52array.reject! { |item| block }
Deletes elements from array for which the block evaluates to true, but returns nil if no changes were made. Equivalent to Array#delete_if.
53array.replace(other_array)
Replaces the contents of array with the contents of other_array, truncating or expanding if necessary.
54array.reverse
Returns a new array containing array's elements in reverse order.
55array.reverse!
Reverses array in place.
56array.reverse_each {|item| block }
Same as Array#each, but traverses array in reverse order.
57array.rindex(obj)
Returns the index of the last object in array == to obj. Returns nil if no match is found.
58array.select {|item| block }
Invokes the block passing in successive elements from array, returning an array containing those elements for which the block returns a true value.
59array.shift
Returns the first element of self and removes it (shifting all other elements down by one). Returns nil if the array is empty.
60array.size
Returns the length of array (number of elements). Alias for length.
61array.slice(index) [or] array.slice(start, length) [or]
array.slice(range) [or] array[index] [or]
array[start, length] [or] array[range]

Returns the element at index, or returns a subarray starting at start and continuing for length elements, 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 (or starting index) are out of range.
62array.slice!(index) [or] array.slice!(start, length) [or]
array.slice!(range)

Deletes the element(s) given by an index (optionally with a length) or by a range. Returns the deleted object, subarray, or nil if index is out of range.
63array.sort [or] array.sort { | a,b | block }
Returns a new array created by sorting self.
64array.sort! [or] array.sort! { | a,b | block }
Sorts self.
65array.to_a
Returns self. If called on a subclass of Array, converts the receiver to an Array object.
66array.to_ary
Returns self.
67array.to_s
Returns self.join.
68array.transpose
Assumes that self is an array of arrays and transposes the rows and columns.
69array.uniq
Returns a new array by removing duplicate values in array.
70array.uniq!
Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).
71array.unshift(obj, ...)
Prepends objects to the front of array, other elements up one.
72array.values_at(selector,...)
Returns an array containing the elements in self corresponding to the given selector (one or more). The selectors may be either integer indices or ranges.
73array.zip(arg, ...) [or]
array.zip(arg, ...){ | arr | block }

Converts any arguments to arrays, then merges elements of array with corresponding elements from each argument.

 

Ruby Array pack directives

Following table lists pack directives for use with Array#pack.

Directive Description
@Moves to absolute position.
AASCII string (space padded, count is width).
aASCII string (null padded, count is width).
BBit string (descending bit order).
bBit string (ascending bit order).
CUnsigned char.
cChar.
D, dDouble-precision float, native format.
EDouble-precision float, little-endian byte order.
eSingle-precision float, little-endian byte order.
F, fSingle-precision float, native format.
GDouble-precision float, network (big-endian) byte order.
gSingle-precision float, network (big-endian) byte order.
HHex string (high nibble first).
hHex string (low nibble first).
IUnsigned integer.
iInteger.
LUnsigned long.
lLong.
MQuoted printable, MIME encoding (see RFC 2045).
mBase64-encoded string.
NLong, network (big-endian) byte order.
nShort, network (big-endian) byte order.
PPointer to a structure (fixed-length string).
pPointer to a null-terminated string.
Q, q64-bit number.
SUnsigned short.
sShort.
UUTF-8.
uUU-encoded string.
VLong, little-endian byte order.
vShort, little-endian byte order.
wBER-compressed integer \fnm.
XBack up a byte.
xNull byte.
ZSame as a, except that null is added with *.

 

Ruby public hash methods

Following are the public hash methods ( Assuming hash is an array object ):

SN Methods with Description
1hash == other_hash
Tests whether two hashes are equal, based on whether they have the same number of key-value pairs, and whether the key-value pairs match the corresponding pair in each hash.
2hash.[key]
Using a key, references a value from hash. If the key is not found, returns a default value.
3hash.[key]=value
Associates the value given by value with the key given by key.
4hash.clear
Removes all key-value pairs from hash.
5hash.default(key = nil)
Returns the default value for hash, nil if not set by default=. ([] returns a default value if the key does not exist in hash.)
6hash.default = obj
Sets a default value for hash.
7hash.default_proc
Returns a block if hash was created by a block.
8hash.delete(key) [or]
array.delete(key) { |key| block }

Deletes a key-value pair from hash by key. If block is used, returns the result of a block if pair is not found. Compare delete_if.
9hash.delete_if { |key,value| block }
Deletes a key-value pair from hash for every pair the block evaluates to true.
10hash.each { |key,value| block }
Iterates over hash, calling the block once for each key, passing the key-value as a two-element array.
11hash.each_key { |key| block }
Iterates over hash, calling the block once for each key, passing key as a parameter.
12hash.each_key { |key_value_array| block }
Iterates over hash, calling the block once for each key, passing the key and value as parameters.
13hash.each_key { |value| block }
Iterates over hash, calling the block once for each key, passing value as a parameter.
14hash.empty?
Tests whether hash is empty (contains no key-value pairs), returning true or false.
15hash.fetch(key [, default] ) [or]
hash.fetch(key) { | key | block }

Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.
16hash.has_key?(key) [or] hash.include?(key) [or]
hash.key?(key) [or] hash.member?(key)

Tests whether a given key is present in hash, returning true or false.
17hash.has_value?(value)
Tests whether hash contains the given value.
18hash.index(value)
Returns the key for the given value in hash, nil if no matching value is found.
19hash.indexes(keys)
Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found. This method is deprecated. Use select.
20hash.indices(keys)
Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found. This method is deprecated. Use select.
21hash.inspect
Returns a pretty print string version of hash.
22hash.invert
Creates a new hash, inverting keys and values from hash; that is, in the new hash, the keys from hash become values, and values become keys.
23hash.keys
Creates a new array with keys from hash.
24hash.length
Returns the size or length of hash as an integer.
25hash.merge(other_hash) [or]
hash.merge(other_hash) { |key, oldval, newval| block }

Returns a new hash containing the contents of hash and other_hash, overwriting pairs in hash with duplicate keys with those from other_hash.
26hash.merge!(other_hash) [or]
hash.merge!(other_hash) { |key, oldval, newval| block }

Same as merge, but changes are done in place.
27hash.rehash
Rebuilds hash based on the current values for each key. If values have changed since they were inserted, this method reindexes hash.
28hash.reject { |key, value| block }
Creates a new hash for every pair the block evaluates to true
29hash.reject! { |key, value| block }
Same as reject, but changes are made in place.
30hash.replace(other_hash)
Replaces the contents of hash with the contents of other_ hash.
31hash.select { |key, value| block }
Returns a new array consisting of key-value pairs from hash for which the block returns true.
32hash.shift
Removes a key-value pair from hash, returning it as a two-element array.
33hash.size
Returns the size or length of hash as an integer.
34hash.sort
Converts hash to a two-dimensional array containing arrays of key-value pairs, then sorts it as an array.
35hash.store(key, value)
Stores a key-value pair in hash.
36hash.to_a
Creates a two-dimensional array from hash. Each key/value pair is converted to an array, and all these arrays are stored in a containing array.
37hash.to_hash
Returns hash (self).
38hash.to_s
Converts hash to an array, then converts that array to a string.
39hash.update(other_hash) [or]
hash.update(other_hash) {|key, oldval, newval| block}

Returns a new hash containing the contents of hash and other_hash, overwriting pairs in hash with duplicate keys with those from other_hash.
40hash.value?(value)
Tests whether hash contains the given value.
41hash.values
Returns a new array containing all the values of hash.
42hash.values_at(obj, ...)
Returns a new array containing the values from hash that are associated with the given key or keys.

 

Regular-expression modifiers:

Regular expression literals may include an optional modifier to control various aspects of matching. The modifier is specified after the second slash character, as shown previously and may be represented by one of these characters:

Modifier Description
iIgnore case when matching text.
oPerform #{} interpolations only once, the first time the regexp literal is evaluated.
xIgnores whitespace and allows comments in regular expressions
mMatches multiple lines, recognizing newlines as normal characters
u,e,s,nInterpret the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. If none of these modifiers is specified, the regular expression is assumed to use the source encoding.

 

Regular-expression patterns:

Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a control character by preceding it with a backslash.

Following table lists the regular expression syntax that is available in Ruby.

Pattern Description
^Matches beginning of line.
$Matches end of line.
.Matches any single character except newline. Using m option allows it to match newline as well.
[...]Matches any single character in brackets.
[^...]Matches any single character not in brackets
re*Matches 0 or more occurrences of preceding expression.
re+Matches 1 or more occurrence of preceding expression.
re?Matches 0 or 1 occurrence of preceding expression.
re{ n}Matches exactly n number of occurrences of preceding expression.
re{ n,}Matches n or more occurrences of preceding expression.
re{ n, m}Matches at least n and at most m occurrences of preceding expression.
a| bMatches either a or b.
(re)Groups regular expressions and remembers matched text.
(?imx)Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?-imx)Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?: re)Groups regular expressions without remembering matched text.
(?imx: re)Temporarily toggles on i, m, or x options within parentheses.
(?-imx: re)Temporarily toggles off i, m, or x options within parentheses.
(?#...)Comment.
(?= re)Specifies position using a pattern. Doesn't have a range.
(?! re)Specifies position using pattern negation. Doesn't have a range.
(?> re)Matches independent pattern without backtracking.
\wMatches word characters.
\WMatches nonword characters.
\sMatches whitespace. Equivalent to [\t\n\r\f].
\SMatches nonwhitespace.
\dMatches digits. Equivalent to [0-9].
\DMatches nondigits.
\AMatches beginning of string.
\ZMatches end of string. If a newline exists, it matches just before newline.
\zMatches end of string.
\GMatches point where last match finished.
\bMatches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.
\BMatches nonword boundaries.
\n, \t, etc.Matches newlines, carriage returns, tabs, etc.
\1...\9Matches nth grouped subexpression.
\10Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.

 

Regular-expression Examples:


Literal characters:

Example Description
/ruby/Match "ruby".
¥Matches Yen sign. Multibyte characters are suported in Ruby 1.9 and Ruby 1.8.

 

Character classes:
Example Description
/[Rr]uby/ Match "Ruby" or "ruby"
/rub[ye]/ Match "ruby" or "rube"
/[aeiou]/Match any one lowercase vowel
/[0-9]/ Match any digit; same as /[0123456789]/
/[a-z]/Match any lowercase ASCII letter
/[A-Z]/Match any uppercase ASCII letter
/[a-zA-Z0-9]/Match any of the above
/[^aeiou]/ Match anything other than a lowercase vowel
/[^0-9]/Match anything other than a digit

 

Special Character Classes:
Example Description
/./ Match any character except newline
/./m In multiline mode . matches newline, too
/\d/Match a digit: /[0-9]/
/\D/ Match a nondigit: /[^0-9]/
/\s/Match a whitespace character: /[ \t\r\n\f]/
/\S/ Match nonwhitespace: /[^ \t\r\n\f]/
/\w/ Match a single word character: /[A-Za-z0-9_]/
/\W/Match a nonword character: /[^A-Za-z0-9_]/

 

Repetition Cases:
Example Description
/ruby?/ Match "rub" or "ruby": the y is optional
/ruby*/ Match "rub" plus 0 or more ys
/ruby+/Match "rub" plus 1 or more ys
/\d{3}/Match exactly 3 digits
/\d{3,}/Match 3 or more digits
/\d{3,5}/Match 3, 4, or 5 digits

 

Greedy & Nongreedy repetition:

This matches the smallest number of repetitions:

Example Description
/<.*>/Greedy repetition: matches "<ruby>perl>"
/<.*?>/ Nongreedy: matches "<ruby>" in "<ruby>perl>"

 

Grouping with parentheses:
Example Description
/\D\d+/ No group: + repeats \d
/(\D\d)+/ Grouped: + repeats \D\d pair
/([Rr]uby(, )?)+/Match "Ruby", "Ruby, ruby, ruby", etc.

 

Backreferences:

This matches a previously matched group again:

Example Description
/([Rr])uby&\1ails/Match ruby&rails or Ruby&Rails
/(['"])[^\1]*\1/Single or double-quoted string. \1 matches whatever the 1st group matched . \2 matches whatever the 2nd group matched, etc.

 

Alternatives:
Example Description
/ruby|rube/Match "ruby" or "rube"
/rub(y|le))/Match "ruby" or "ruble"
/ruby(!+|\?)/ "ruby" followed by one or more ! or one ?

 

Anchors:

This need to specify match position

Example Description
/^Ruby/Match "Ruby" at the start of a string or internal line
/Ruby$/ Match "Ruby" at the end of a string or line
/\ARuby/ Match "Ruby" at the start of a string
/Ruby\Z/Match "Ruby" at the end of a string
/\bRuby\b/Match "Ruby" at a word boundary
/\brub\B/\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
/Ruby(?=!)/Match "Ruby", if followed by an exclamation point
/Ruby(?!!)/ Match "Ruby", if not followed by an exclamation point

 

Special syntax with parentheses:
Example Description
/R(?#comment)/ Matches "R". All the rest is a comment
/R(?i)uby/ Case-insensitive while matching "uby"
/R(?i:uby)/ Same as above
/rub(?:y|le))/Group only without creating \1 backreference

 

Time Formatting Directives:

These directives in the following table are used with the method Time.strftime.

Directive Description
%aThe abbreviated weekday name (Sun).
%AThe full weekday name (Sunday).
%bThe abbreviated month name (Jan).
%BThe full month name (January).
%cThe preferred local date and time representation.
%dDay of the month (01 to 31).
%HHour of the day, 24-hour clock (00 to 23).
%IHour of the day, 12-hour clock (01 to 12).
%jDay of the year (001 to 366).
%mMonth of the year (01 to 12).
%MMinute of the hour (00 to 59).
%pMeridian indicator (AM or PM).
%SSecond of the minute (00 to 60).
%UWeek number of the current year, starting with the first Sunday as the first day of the first week (00 to 53).
%WWeek number of the current year, starting with the first Monday as the first day of the first week (00 to 53).
%wDay of the week (Sunday is 0, 0 to 6).
%xPreferred representation for the date alone, no time.
%XPreferred representation for the time alone, no date.
%yYear without a century (00 to 99).
%YYear with century.
%ZTime zone name.
%%Literal % character.