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.
| END | else | nill | true |
| alias | elsif | not | undef |
| and | end | or | unless |
| begin | ensure | redo | until |
| break | false | rescue | when |
| case | for | retry | while |
| class | if | return | while |
| def | in | self | __FILE__ |
| defined? | module | super | __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 |
|---|---|---|
| \a | 0x07 | Bell or alert |
| \b | 0x08 | Backspace |
| \cx | Control-x | |
| \C-x | Control-x | |
| \e | 0x1b | Escape |
| \f | 0x0c | Formfeed |
| \M-\C-x | Meta-Control-x | |
| \n | 0x0a | Newline |
| \nnn | Octal notation, where n is in the range 0.7 | |
| \r | 0x0d | Carriage return |
| \s | 0x20 | Space |
| \t | 0x09 | Tab |
| \v | 0x0b | Vertical 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 |
|---|---|
| a | ASCII (same as none). This is the default. |
| e | EUC. |
| n | None (same as ASCII). |
| u | UTF-8. |
String Built-in Methods:
Following are the public String methods ( Assuming str is a String object ):
| SN | Methods with Description |
|---|---|
| 1 | str % 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." |
| 2 | str * integer Returns a new string containing integer times str. In other words, str is repeated integer imes. |
| 3 | str + other_str Concatenates other_str to str. |
| 4 | str << 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. |
| 5 | str <=> other_str Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is casesensitive. |
| 6 | str == obj Tests str and obj for equality. If obj is not a String, returns false; returns true if str <=> obj returns 0. |
| 7 | str =~ obj Matches str against a regular expression pattern obj. Returns the position where the match starts; otherwise, false. |
| 8 | str =~ obj Matches str against a regular expression pattern obj. Returns the position where the match starts; otherwise, false. |
| 9 | str.capitalize Capitalizes a string. |
| 10 | str.capitalize! Same as capitalize, but changes are made in place. |
| 11 | str.casecmp Makes a case-insensitive comparison of strings. |
| 12 | str.center Centers a string. |
| 13 | str.chomp Removes the record separator ($/), usually \n, from the end of a string. If no record separator exists, does nothing. |
| 14 | str.chomp! Same as chomp, but changes are made in place. |
| 15 | str.chop Removes the last character in str. |
| 16 | str.chop! Same as chop, but changes are made in place. |
| 17 | str.concat(other_str) Concatenates other_str to str. |
| 18 | str.count(str, ...) Counts one or more sets of characters. If there is more than one set of characters, counts the intersection of those sets |
| 19 | str.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 /. |
| 20 | str.delete(other_str, ...) Returns a copy of str with all characters in the intersection of its arguments deleted. |
| 21 | str.delete!(other_str, ...) Same as delete, but changes are made in place. |
| 22 | str.downcase Returns a copy of str with all uppercase letters replaced with lowercase. |
| 23 | str.downcase! Same as downcase, but changes are made in place. |
| 24 | str.dump Returns a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped. |
| 25 | str.each(separator=$/) { |substr| block } Splits str using argument as the record separator ($/ by default), passing each substring to the supplied block. |
| 26 | str.each_byte { |fixnum| block } Passes each byte from str to the block, returning each byte as a decimal representation of the byte. |
| 27 | str.each_line(separator=$/) { |substr| block } Splits str using argument as the record separator ($/ by default), passing each substring to the supplied block. |
| 28 | str.empty? Returns true if str is empty (has a zero length). |
| 29 | str.eql?(other) Two strings are equal if the have the same length and content. |
| 30 | str.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') |
| 31 | str[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. |
| 32 | str[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!. |
| 33 | str.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. |
| 34 | str.hash Returns a hash based on the string's length and content. |
| 35 | str.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. |
| 36 | str.include? other_str [or] str.include? fixnum Returns true if str contains the given string or character. |
| 37 | str.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. |
| 38 | str.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. |
| 39 | str.inspect Returns a printable version of str, with special characters escaped. |
| 40 | str.intern [or] str.to_sym Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. |
| 41 | str.length Returns the length of str. Compare size. |
| 42 | str.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. |
| 43 | str.lstrip Returns a copy of str with leading whitespace removed. |
| 44 | str.lstrip! Removes leading whitespace from str, returning nil if no change was made. |
| 45 | str.match(pattern) Converts pattern to a Regexp (if it isn't already one), then invokes its match method on str. |
| 46 | str.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. |
| 47 | str.replace(other_str) Replaces the contents and taintedness of str with the corresponding values in other_str. |
| 48 | str.reverse Returns a new string with the characters from str in reverse order. |
| 49 | str.reverse! Reverses str in place. |
| 50 | str.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. |
| 51 | str.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. |
| 52 | str.rstrip Returns a copy of str with trailing whitespace removed. |
| 53 | str.rstrip! Removes trailing whitespace from str, returning nil if no change was made. |
| 54 | str.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. |
| 55 | str.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. |
| 56 | str.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. |
| 57 | str.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. |
| 58 | str.squeeze!([other_str]*) Squeezes str in place, returning either str, or nil if no changes were made. |
| 59 | str.strip Returns a copy of str with leading and trailing whitespace removed. |
| 60 | str.strip! Removes leading and trailing whitespace from str. Returns nil if str was not altered. |
| 61 | str.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. |
| 62 | str.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. |
| 63 | str.succ [or] str.next Returns the successor to str. |
| 64 | str.succ! [or] str.next! Equivalent to String#succ, but modifies the receiver in place. |
| 65 | str.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. |
| 66 | str.swapcase Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase. |
| 67 | str.swapcase! Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made. |
| 68 | str.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. |
| 69 | str.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. |
| 70 | str.to_s [or] str.to_str Returns the receiver. |
| 71 | str.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. |
| 72 | str.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. |
| 73 | str.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. |
| 74 | str.tr_s!(from_str, to_str) Performs String#tr_s processing on str in place, returning str, or nil if no changes were made. |
| 75 | str.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. |
| 76 | str.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. |
| 77 | str.upcase! Changes the contents of str to uppercase, returning nil if no changes are made. |
| 78 | str.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 |
|---|---|---|
| A | String | With trailing nulls and spaces removed. |
| a | String | String. |
| B | String | Extract bits from each character (most significant bit first). |
| b | String | Extract bits from each character (least significant bit first). |
| C | Fixnum | Extract a character as an unsigned integer. |
| c | Fixnum | Extract a character as an integer. |
| D, d | Float | Treat sizeof(double) characters as a native double. |
| E | Float | Treat sizeof(double) characters as a double in littleendian byte order. |
| e | Float | Treat sizeof(float) characters as a float in littleendian byte order. |
| F, f | Float | Treat sizeof(float) characters as a native float. |
| G | Float | Treat sizeof(double) characters as a double in network byte order. |
| g | String | Treat sizeof(float) characters as a float in network byte order. |
| H | String | Extract hex nibbles from each character (most significant bit first) |
| h | String | Extract hex nibbles from each character (least significant bit first). |
| I | Integer | Treat sizeof(int) (modified by _) successive characters as an unsigned native integer. |
| i | Integer | Treat sizeof(int) (modified by _) successive characters as a signed native integer. |
| L | Integer | Treat four (modified by _) successive characters as an unsigned native long integer. |
| l | Integer | Treat four (modified by _) successive characters as a signed native long integer. |
| M | String | Quoted-printable. |
| m | String | Base64-encoded. |
| N | Integer | Treat four characters as an unsigned long in network byte order. |
| n | Fixnum | Treat two characters as an unsigned short in network byte order. |
| P | String | Treat sizeof(char *) characters as a pointer, and return \emph{len} characters from the referenced location. |
| p | String | Treat sizeof(char *) characters as a pointer to a nullterminated string. |
| Q | Integer | Treat eight characters as an unsigned quad word (64 bits). |
| q | Integer | Treat eight characters as a signed quad word (64 bits). |
| S | Fixnum | Treat two (different if _ used) successive characters as an unsigned short in native byte order. |
| s | Fixnum | Treat two (different if _ used) successive characters as a signed short in native byte order. |
| U | Integer | UTF-8 characters as unsigned integers. |
| u | String | UU-encoded. |
| V | Fixnum | Treat four characters as an unsigned long in little-endian byte order. |
| v | Fixnum | Treat two characters as an unsigned short in little-endian byte order. |
| w | Integer | BER-compressed integer. |
| X | Skip backward one character. | |
| x | Skip forward one character. | |
| Z | String | With 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. |
| or | Called 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. |
| not | 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. | 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 |
|---|---|
| 1 | array & other_array Returns a new array containing elements common to the two arrays, with no duplicates. |
| 2 | array * 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). |
| 3 | array + other_array Returns a new array built by concatenating the two arrays together to produce a third array. |
| 4 | array . other_array Returns a new array that is a copy of the original array, removing any items that also appear in other_array. |
| 5 | str <=> other_str Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is casesensitive. |
| 6 | array | other_array Returns a new array by joining array with other_array, removing duplicates. |
| 7 | array << obj Pushes the given object onto the end of array. This expression returns the array itself, so several appends may be chained together. |
| 8 | array <=> other_array Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than other_array. |
| 9 | array == 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. |
| 10 | array[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. |
| 11 | array[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. |
| 12 | array.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. |
| 13 | array.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. |
| 14 | array.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. |
| 15 | array.clear Removes all elements from array. |
| 16 | array.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. |
| 17 | array.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. |
| 18 | array.compact Returns a copy of self with all nil elements removed. |
| 19 | array.compact! Removes nil elements from array. Returns nil if no changes were made. |
| 20 | array.concat(other_array) Appends the elements in other_array to self. |
| 21 | array.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. |
| 22 | array.delete_at(index) Deletes the element at the specified index, returning that element, or nil if the index is out of range. |
| 23 | array.delete_if { |item| block } Deletes every element of self for which block evaluates to true. |
| 24 | array.each { |item| block } Calls block once for each element in self, passing that element as a parameter. |
| 25 | array.each_index { |index| block } Same as Array#each, but passes the index of the element instead of the element itself. |
| 26 | array.empty? Returns true if the self array contains no elements. |
| 27 | array.eql?(other) Returns true if array and other are the same object, or are both arrays with the same content. |
| 28 | array.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. |
| 29 | array.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. |
| 30 | array.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. |
| 31 | array.flatten Returns a new array that is a one-dimensional flattening of this array (recursively). |
| 32 | array.flatten! Flattens array in place. Returns nil if no modifications were made. (array contains no subarrays.) |
| 33 | array.frozen? Returns true if array is frozen (or temporarily frozen while being sorted). |
| 34 | array.hash Compute a hash-code for array. Two arrays with the same content will have the same hash code |
| 35 | array.include?(obj) Returns true if obj is present in self, false otherwise. |
| 36 | array.index(obj) Returns the index of the first object in self that is == to obj. Returns nil if no match is found. |
| 37 | array.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. |
| 38 | array.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. |
| 39 | array.insert(index, obj...) Inserts the given values before the element with the given index (which may be negative). |
| 40 | array.inspect Creates a printable version of array. |
| 41 | array.join(sep=$,) Returns a string created by converting each element of the array to a string, separated by sep. |
| 42 | array.last [or] array.last(n) Returns the last element(s) of self. If array is empty, the first form returns nil. |
| 43 | array.length Returns the number of elements in self. May be zero. |
| 44 | array.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. |
| 45 | array.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. |
| 46 | array.nitems Returns the number of non-nil elements in self. May be zero. |
| 47 | array.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 ) |
| 48 | array.pop Removes the last element from array and returns it, or nil if array is empty. |
| 49 | array.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. |
| 50 | array.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. |
| 51 | array.reject { |item| block } Returns a new array containing the items array for which the block is not true. |
| 52 | array.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. |
| 53 | array.replace(other_array) Replaces the contents of array with the contents of other_array, truncating or expanding if necessary. |
| 54 | array.reverse Returns a new array containing array's elements in reverse order. |
| 55 | array.reverse! Reverses array in place. |
| 56 | array.reverse_each {|item| block } Same as Array#each, but traverses array in reverse order. |
| 57 | array.rindex(obj) Returns the index of the last object in array == to obj. Returns nil if no match is found. |
| 58 | array.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. |
| 59 | array.shift Returns the first element of self and removes it (shifting all other elements down by one). Returns nil if the array is empty. |
| 60 | array.size Returns the length of array (number of elements). Alias for length. |
| 61 | array.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. |
| 62 | array.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. |
| 63 | array.sort [or] array.sort { | a,b | block } Returns a new array created by sorting self. |
| 64 | array.sort! [or] array.sort! { | a,b | block } Sorts self. |
| 65 | array.to_a Returns self. If called on a subclass of Array, converts the receiver to an Array object. |
| 66 | array.to_ary Returns self. |
| 67 | array.to_s Returns self.join. |
| 68 | array.transpose Assumes that self is an array of arrays and transposes the rows and columns. |
| 69 | array.uniq Returns a new array by removing duplicate values in array. |
| 70 | array.uniq! Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found). |
| 71 | array.unshift(obj, ...) Prepends objects to the front of array, other elements up one. |
| 72 | array.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. |
| 73 | array.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. |
| A | ASCII string (space padded, count is width). |
| a | ASCII string (null padded, count is width). |
| B | Bit string (descending bit order). |
| b | Bit string (ascending bit order). |
| C | Unsigned char. |
| c | Char. |
| 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 RFC 2045). |
| m | Base64-encoded string. |
| 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 \fnm. |
| X | Back up a byte. |
| x | Null byte. |
| Z | Same 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 |
|---|---|
| 1 | hash == 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. |
| 2 | hash.[key] Using a key, references a value from hash. If the key is not found, returns a default value. |
| 3 | hash.[key]=value Associates the value given by value with the key given by key. |
| 4 | hash.clear Removes all key-value pairs from hash. |
| 5 | hash.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.) |
| 6 | hash.default = obj Sets a default value for hash. |
| 7 | hash.default_proc Returns a block if hash was created by a block. |
| 8 | hash.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. |
| 9 | hash.delete_if { |key,value| block } Deletes a key-value pair from hash for every pair the block evaluates to true. |
| 10 | hash.each { |key,value| block } Iterates over hash, calling the block once for each key, passing the key-value as a two-element array. |
| 11 | hash.each_key { |key| block } Iterates over hash, calling the block once for each key, passing key as a parameter. |
| 12 | hash.each_key { |key_value_array| block } Iterates over hash, calling the block once for each key, passing the key and value as parameters. |
| 13 | hash.each_key { |value| block } Iterates over hash, calling the block once for each key, passing value as a parameter. |
| 14 | hash.empty? Tests whether hash is empty (contains no key-value pairs), returning true or false. |
| 15 | hash.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. |
| 16 | hash.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. |
| 17 | hash.has_value?(value) Tests whether hash contains the given value. |
| 18 | hash.index(value) Returns the key for the given value in hash, nil if no matching value is found. |
| 19 | hash.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. |
| 20 | hash.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. |
| 21 | hash.inspect Returns a pretty print string version of hash. |
| 22 | hash.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. |
| 23 | hash.keys Creates a new array with keys from hash. |
| 24 | hash.length Returns the size or length of hash as an integer. |
| 25 | hash.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. |
| 26 | hash.merge!(other_hash) [or] hash.merge!(other_hash) { |key, oldval, newval| block } Same as merge, but changes are done in place. |
| 27 | hash.rehash Rebuilds hash based on the current values for each key. If values have changed since they were inserted, this method reindexes hash. |
| 28 | hash.reject { |key, value| block } Creates a new hash for every pair the block evaluates to true |
| 29 | hash.reject! { |key, value| block } Same as reject, but changes are made in place. |
| 30 | hash.replace(other_hash) Replaces the contents of hash with the contents of other_ hash. |
| 31 | hash.select { |key, value| block } Returns a new array consisting of key-value pairs from hash for which the block returns true. |
| 32 | hash.shift Removes a key-value pair from hash, returning it as a two-element array. |
| 33 | hash.size Returns the size or length of hash as an integer. |
| 34 | hash.sort Converts hash to a two-dimensional array containing arrays of key-value pairs, then sorts it as an array. |
| 35 | hash.store(key, value) Stores a key-value pair in hash. |
| 36 | hash.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. |
| 37 | hash.to_hash Returns hash (self). |
| 38 | hash.to_s Converts hash to an array, then converts that array to a string. |
| 39 | hash.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. |
| 40 | hash.value?(value) Tests whether hash contains the given value. |
| 41 | hash.values Returns a new array containing all the values of hash. |
| 42 | hash.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 |
|---|---|
| i | Ignore case when matching text. |
| o | Perform #{} interpolations only once, the first time the regexp literal is evaluated. |
| x | Ignores whitespace and allows comments in regular expressions |
| m | Matches multiple lines, recognizing newlines as normal characters |
| u,e,s,n | Interpret 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| b | Matches 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. |
| \w | Matches word characters. |
| \W | Matches nonword characters. |
| \s | Matches whitespace. Equivalent to [\t\n\r\f]. |
| \S | Matches nonwhitespace. |
| \d | Matches digits. Equivalent to [0-9]. |
| \D | Matches nondigits. |
| \A | Matches beginning of string. |
| \Z | Matches end of string. If a newline exists, it matches just before newline. |
| \z | Matches end of string. |
| \G | Matches point where last match finished. |
| \b | Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. |
| \B | Matches nonword boundaries. |
| \n, \t, etc. | Matches newlines, carriage returns, tabs, etc. |
| \1...\9 | Matches nth grouped subexpression. |
| \10 | Matches 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 |
|---|---|
| %a | The abbreviated weekday name (Sun). |
| %A | The full weekday name (Sunday). |
| %b | The abbreviated month name (Jan). |
| %B | The full month name (January). |
| %c | The preferred local date and time representation. |
| %d | Day of the month (01 to 31). |
| %H | Hour of the day, 24-hour clock (00 to 23). |
| %I | Hour of the day, 12-hour clock (01 to 12). |
| %j | Day of the year (001 to 366). |
| %m | Month of the year (01 to 12). |
| %M | Minute of the hour (00 to 59). |
| %p | Meridian indicator (AM or PM). |
| %S | Second of the minute (00 to 60). |
| %U | Week number of the current year, starting with the first Sunday as the first day of the first week (00 to 53). |
| %W | Week number of the current year, starting with the first Monday as the first day of the first week (00 to 53). |
| %w | Day of the week (Sunday is 0, 0 to 6). |
| %x | Preferred representation for the date alone, no time. |
| %X | Preferred representation for the time alone, no date. |
| %y | Year without a century (00 to 99). |
| %Y | Year with century. |
| %Z | Time zone name. |
| %% | Literal % character. |


