– Page consists of tables. Each table is a part of manual (like “Regular Expressions”). The left column of the table is for descriptions and syntax, and right is for samples. They are parallel, so on the right side of the table you can find using of features described on the left side. Also table can be divided into rows. And in every cell you can find many records with own title and keyword-line. In description side the title is yellow if describes a syntax and blue if it is just a text title (name of feature, etc).

? What does 1^3 mean

– It means "one of three", these numbers help you to know how many places with your keyword are on the page, so you won't worry that you are searching again from the beginning by pressing Down/Left/F3.

? There isn't keyword I'm looking for...

– So you are really lucky! Some time later it will be very difficult to find a keyword which will be absent from this page, so now you have a great chance to become the first to add something for this keyword.

? "Scripts loaded" indicator

– Yes, while scripts are loading, the search doesn't work properly. The pink vertical line on the left side of the page becomes red, when the scripts are loaded, so then you can start typing for searching.

? Case-sensitive matching

– For now, case-sensitive matching is automatically enabled, when there is an uppercase chars in the word. So "Ruby" will match only "Ruby", when "ruby" will match "ruby" and "Ruby" and "ruBy".

? I can modify it... for what?

– This page is designed for you and its destiny is only in your hands... So if you are not so lazy as others, if you like Ruby and have some interesting and useful samples, or you have found or can write some description – just do few clicks and become a part of this page (no registration and no authorization is required, just Flash). Only together we can make this page really useful for us.

? I don’t see any tools for modifying

– Switch to "Edit mode" via button on the top of the page, or pressing F2, and then just use your mouse, attention and some intuition – and you will find all the hidden buttons :) Then you can read the button tips for a description. This map may help you...

? Why I can edit every thing, not just my own records

– If you will find a mistake in any text, it would be good for you to correct it. Or you can add something to someone's text.

? So I can add anything I want

– Yes, but it would be good for you to check if there already is such sample or description on the page (by searching by keyword).

? When will my changes appear on the page

– All changes will be pre-moderated, so it can take from 3 minutes to few hours.
And only then your keywords will be indexed for searching.

? Does it have an undelete or version control feature

– Yes it saves all versions of each block, and monitors all the actions on the page. So moderator can restore any version of block, or can cancel deleting, or can delete any spam, before it will appear on the original page. And every time, when you load the main page – it is a cached page of the last generated moderated version.

? How to set a keyword not in keyword-line

– You can select your word (the easiest way – by double-clicking) and click on the "key" button of pop-up menu.

? Is it possible to create analogue page for other languages

– Yes, if this page become useful. It can be anything (programming language, specification, standard...) and in any language (localization), and it needs community, moderator and some financial support for hosting.

? How to ask question, report a bug or just say something

– You can use the "Leave feedback" form on the right side of the top of this page, or you can e-mail me.

? Why Ruby

– It's all because of Ruby :)

? Are you using Ajax

– No, just Flash and JS.

? Why does the "feedback form" hide when editor appears

– It’s because of problems with ‘window’ and ‘transparent’ modes of .swf on page.

? Why beta

– I really need to rewrite all the code to improve performance and functionality, and make it cross-browser. Also there must be a search for multiple keywords, etc...

? Any recommendations

– If you need to find some short word (like "=" or "&") – just put space after it when typing
– HOME – go to the first, END – to the last, ESC – new search
– Links are allowed only in body of description. To write link – just write it (no tags needed)
– Don’t use the same keyword in description/code, then in the title and then in the keyword-line.

0^0

!sk

Page was updated on the server.You have to refresh the page to see changes.You can click here to refresh.

+

~

-

+

+

~

-

+

+

-

+

Undo last deleting

Changes will appear on the original page in 3m-10h.Don't refresh the page if you want to continue work with your current changes(click to minimize this message)

Ruby[about]

What is Ruby?

– Ruby is a reflective, dynamic, object-oriented programming language. It combines syntax inspired by Perl with Smalltalk-like object-oriented features, and also shares some features with Python, Lisp, Dylan and CLU. Ruby is a single-pass interpreted language. Its main implementation is free software. (en.wikipedia.org/wiki/Ruby_programming_language)
– A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. (ruby-lang.org)
– Ruby is a an exciting new, pure, object oriented programming language. While few people in the West have heard of Ruby yet, it has taken off like wildfire in Japan – already overtaking the Python language in popularity. (rubycentral.com)

comment# Ruby treats nil as a false value in conditions,# you could write the following to process the lines in a file.

1111

11a =10
b =20
c = a + b
puts c

rp

hello

Assignment

– An assignment statement sets the variable or attribute on its left side (the lvalue) to refer to the value on the right (the rvalue). It then returns that value as the result of the assignment expression. This means you can chain assignments, and you can perform assignments in some unexpected places.
– In older Ruby versions, the result of the assignment was the value returned by the attribute-setting method. In Ruby 1.8, the value of the assignment is always the value of the parameter; the return value of the method is discarded.
– Ruby assignments are effectively performed in parallel, so the values assigned are not affected by the assignment itself. The values on the right side are evaluated in the order in which they appear before any assignment is made to variables or attributes on the left.
– When an assignment has more than one lvalue, the assignment expression returns an array of the rvalues. If an assignment contains more lvalues than rvalues, the excess lvalues are set to nil. If a multiple assignment contains morervalues than lvalues, the extra rvalues are ignored. If an assignment has just onelvalue and multiple rvalues, the rvalues are converted to an array and assigned to the lvalue.
– In common with many other languages, Ruby has a syntactic shortcut: a = a + 2 may be written as a += 2.
– Something you won’t find in Ruby are the autoincrement (++) and autodecrement (--) operators of C and Java. Use the += and -= forms instead.

return value of the method is discardedclass Test
def val=(val) #creates only writable member of class
@val = val
return 99
end
end
t = Test.new
a = t.val = 2
a #-->2

Returning

Anything that can reasonably return a value does.
The if and case statements both return the value of the last expression executed

An assignment expression may have one or more lvalues and one or more rvalues. This section explains how Ruby handles assignment with different combinations of arguments.
1. If the last rvalue is prefixed with an asterisk and is an object of class Array, the rvalue is replaced with the elements of the array, with each element forming its own rvalue.
2. If the assignment contains multiple lvalues and one rvalue, the rvalue is converted into an Array, and this array is expanded into a set of rvalues as described in (1).
3. Successive rvalues are assigned to the lvalues. This assignment effectively happens in parallel, so that (for example) a,b=b,a swaps the values in "a" and "b."
4. If there are more lvalues than rvalues, the excess will have nil assigned to them.
5. If there are more rvalues that lvalues, the excess will be ignored.
6. These rules are modified slightly if the last lvalue is preceded with an asterisk. This lvalue will always receive an array during the assignment. The array will consist of whatever rvalue would normally have been assigned to this lvalue, followed by the excess rvalues (if any).
7. If an lvalue is a parenthesized list, it is treated as a nested assignment statement, and the list is assigned from the corresponding rvalue as described by these rules.

Collapse and expandarrays using parallelassignment

You can collapse and expand arrays using Ruby’s parallel assignment operator.
If the last lvalue is preceded by an asterisk, all the remaining rvalues will be collected and assigned to that lvalue as an array.
Similarly, if the last rvalue is an array, you can prefix it with an asterisk, which effectively expands it into its constituent values in place. (This is not necessary if the rvalue is the only thing on the right side—the array will be expanded automatically.)

Parallel assignments have one more feature worth mentioning. The left-hand side of an assignment may contain a parenthesized list of terms. Ruby treats these terms as if they were a nested assignment statement. It extracts out the corresponding rvalue, assigning it to the parenthesized terms, before continuing with the higher-level assignment.

== Test for equal value.
=== Used to compare the each of the items with the target in the when clause of a case statement.
<=> General comparison operator. Returns -1, 0, or +1, depending on whether its receiver is less than, equal to, or greater than its argument.
<, <=, >=, > Comparison operators for less than, less than or equal, greater than or equal, and greater than.
=~ Regular expression pattern match.
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.
– Both == and =~ have negated forms, != and !~. However, these are converted by Ruby when your program is read. a != b is equivalent to !(a == b), and a !~ b is the same as !(a =~ b). This means that if you write a class that overrides == or =~ you get a working != and !~ for free. But on the flip side, this also means that you cannot define != and !~ independent of == and =~, respectively.
– You can use a Ruby range as a boolean expression. A range such as exp1..exp2 will evaluate as false until exp1 becomes true. The range will then evaluate as true until exp2 becomes true. Once this happens, the range resets, ready to fire again. We show some examples of this on page

equality

obj == otherObj → true or false

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

.equal?

obj.equal?(otherObj) → true or false

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) if a is the same object as b).

.eql?

obj.eql?(otherObj) → true or false

The eql? method returns true if obj and otherObj have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:
1 == 1.0 #-> true
1.eql? 1.0 #-> false

document here, here document, HereDoc

Heredocument

A here document consists of lines in the source up to, but not including, the terminating string that you specify after the << characters. Normally, this terminator must start in the first column. However, if you put a minus sign after the << characters (<<-), you can indent the terminator.
Strings can continue across multiple input lines, in which case they will contain newline characters. It is also possible to use here documents to express long string literals. Whenever Ruby parses the sequence <<identifier or <<quoted string, it replaces it with a string literal built from successive logical input lines. It stops building the string when it finds a line that starts with the identifier or the quoted string. You can put a minus sign immediately after the << characters, in which case the terminator can be indented from the left margin. If a quoted string was used to specify the terminator, its quoting rules will be applied to the here document; otherwise, double-quoting rules apply.

here documentaString = <<END_OF_STRING
The body of the string
is the input lines up to
one ending with the same
text that followed the '<<'
END_OF_STRING

Compares two values, returning -1, 0, or +1 depending on whether the first is less than, equal to, or greater than the second.

$_ variable

Globalvariable $_

This uses some behind-the-scenes magic behavior: gets assigns the last line read to the global variable $_, the ~ operator does a regular expression match against $_, and print with no arguments prints $_.file = File.open("ordinal")
while file.gets
print if ~/third/ .. ~/fifth/
end

BEGIN and END Blocks

Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finishedexecuting (the END blocks).
– A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order.

There are alternative forms of literal strings, arrays, regular expressions, and shellcommands that are specified using a generalized delimited syntax.
– All these literals start with a percent character, followed by a single character that identifies the literal's type.
– Following the type character is a delimiter, which can be any character.
– If the delimiter is one of the characters "(", "[", "{", or "<", the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character.
– Delimited strings may continue over multiple lines.
%q – Single-quoted string
%Q, % – Double-quoted string
%w – Array of tokens
%W – Array of tokens with substitutions
%r – Regular expression pattern
%x – Shellcommand

A Ruby symbol is the internal representation of a name. You construct the symbol for a name by preceding the name with a colon.
– A particular name will always generate the same symbol, regardless of how that name is used within the program.
– Other languages call this process "interning" and call symbols "atoms".

symbols:Object
:myVariable

Boolean Expressions

0

Conditional Execution

– Ruby has a simple definition of truth. Any value that is notnil or the constant false is true.
– However, C, C++, and Perl programmers sometimes fall into a trap. The numberzerois not interpreted as a false value. Neither is azero-length string. This can be a tough habit to break.

– In the text, we said things such as "and evaluates to true if both operands are true." But it’s actually slightly more subtle than that. The operators and, or, && and || actually return the first of their arguments that determine the truth or falsity of the condition. Sounds grand.What does it mean?
Take the expression "val1 and val2". If val1 is either false or nil, then we know the expression cannot be true. In this case, the value of val1 determines the overall value of the expression, so it is the value returned. If val1 has some other value, then the overall value of the expression depends on val2, so its value is returned.
– Note that despite all this magic, the overall truth value of the expression is correct.
– The same evaluation takes place for or (except an or expression’s value is known early if val1 is not false).

Both and and && evaluate to true only if both operands are true.
They evaluate the second operand only if the first is true (this is sometimes known as shortcircuit evaluation).
The only difference in the two forms is precedence (and binds lower than &&).

||, or

Similarly, both or and || evaluate to true if either operand is true.
They evaluate their second operand only if the first is false.
As with and, the only difference between or and || is their precedence.
– Just to make life interesting, and and or have the same precedence, and && has a higher precedence than ||.

!, not

not and ! return the opposite of their operand (false if the operand is true, and true if the operand is false).
And, yes, not and ! differ only in precedence.

Returns nil if its argument (which can be an arbitrary expression) is not defined; otherwise it returns a description of that argument.
If the argument is yield, defined? returns the string "yield" if a code block is associated with the current context.

Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods.
The same Symbol object will be created for a given name or string for the duration of a program's execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.
In general, to_sym returns the Symbol corresponding to an object. As sym is already a symbol, self is returned in this case.

The Symbol :Fred will be the same object in all three contextsmodule One
class Fred
end
$f1 = :Fred
end
module Two
Fred = 1
$f2 = :Fred
end
def Fred()
end
$f3 = :Fred
$f1.id #-> 2514190
$f2.id #-> 2514190
$f3.id #-> 2514190

about symbols

Understanding Ruby Symbols

If you are familiar with C, you can think about symbol like about some enum value. The purpose is the same: to have a descriptive name but use only an identifier (same everywhere) behind it, which use much less memory than appropriate string variable.
"Simply, a symbol is something that you use to represent names and strings. What this boils down to is a way to efficiently have descriptive names while saving the space one would use to generate a string for each naming instance."
Read full post "Understanding Ruby Symbols" by Kevin Clark
glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols
"Say you're creating thousands of hashes to represent a common JSON object – a temperature reading. They all have the same key structure, but the data differ.
sea = {'lat' => 47.53, 'lon' => 122.30, 'temp' => 15.0}
sf = {'lat' => 37.79, 'lon' => 122.41, 'temp' => 25.0}
puts sea.keys[0] == sf.keys[0] # true
puts sea.keys[0].object_id # 86288110
puts sf.keys[0].object_id # 86345290
So it's 15°C in Seattle and 25°C in San Francisco. Typical. What's more interesting is that although your keys are equal, they are two different String objects. With 1,000,000 such hashes, you're carrying around 3,000,000 strings that take up a lot more space than the Float entries.
Symbols solve this issue. At the C level of Ruby, each symbol maps to an unsigned integer – the symbol table has one entry per symbol, and the entries exist as long as the process lives.
So, how should Symbols be used?
Common values that are used often/repeatedly for identity (i.e. our temperature hash keys) should be Symbols. They're all about identity."
Read full post "Memory and Ruby :symbols" by Brendan Ribera
threebrothers.org/brendan/blog/memory-and-ruby-symbols

Is a variable an object? In Ruby, the answer is “no.” A variable is simply a reference to an object. Objects float around in a big pool somewhere (the heap, most of the time) and are pointed to by variables.

Naming rules

Name can be any combination of letters, digits, and underscores (with the proviso that the character following an @ sign may not be a digit). However, by convention multiword instances variables are written with underscores between the words, and multiword class names are written in MixedCase (with each word capitalized).

Class variable.
Unlike global and instance variables, class variables must be initialized before they are used.

Class variables@@varname
@@V
@@TO_ALL
@@v_name

ClassName, ModuleName, ConstName

Class names, module names, and constants must start with an uppercase letter.

samplePI
String
MyClass
RModule

Array class[Array, Array class, arrays, list, rray]

about

The class Array holds a collection of object references. Each object reference occupies a position in the array, identified by a non-negative integer index.
It’s more efficient to access array elements, but hashes provide more flexibility
– Literals of class Array are created by placing a comma-separated series of object references between square brackets.
– A trailing comma is ignored.
– Arrays of strings can be constructed using a shortcut notation, %w, which extracts space-separated tokens into successive elements of the array. A space can be escaped with a backslash. This is a form of general delimited input.

.., ..., two periods

Indexingelements

– Ruby array index starts at zero.
– Index an array with a non-negative integer, and it returns the object at that position or returns nil if nothing is there.
– Index an array with a negative integer, and it counts from the end. A negative index is assumed to be relative to the end of the array — that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.
– You can also index arrays with a pair of numbers, [start, count]. This returns a new array consisting of references to count objects starting at position start.
– You can index arrays using ranges, in which start and end positions are separated by two or three periods. The two-period form includes the end position, and the three-period form does not.

remove

Modifyingelements in array

– The [ ] operator has a corresponding [ ]= operator, which lets you setelements in the array. If used with a single integer index, the element at that position is replaced by whatever is on the right side of the assignment. Any gaps that result will be filled with nil.
– If the index to [ ]= is two numbers (a start and a length) or a range, then those elements in the original array are replaced by whatever is on the right side of the assignment. If the length is zero, the right side is inserted into the array before the start position; no elements are removed. If the right side is itself an array, its elements are used in the replacement. The array size is automatically adjusted if the index selects a different number of elements than are available on the right side of the assignment.

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

Sample[1, 2, 3] + [4, 5] #-> [1, 2, 3, 4, 5]

- array, array -

array_1 - array_2 → array

Difference — returns a new array that is a copy of the original array, removing any items that also appear in other_array.
(If you need set-like behavior, see the library class Set.)

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

<< array, array<<, push

array << obj → array

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

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

<=>array, array<=>

array_1 <=> array_2 → -1, 0, +1

Comparison — returns an integer (-1, 0, or +1) if this array_1 is less than, equal to, or greater than array_2.
Each object in each array is compared (using <=>). If any value isn’t equal, then that inequality is the return value. If all the values found are equal, then the return is based on a comparison of the array lengths. Thus, two arrays are “equal” according to Array#<=> if and only if they have the same length and the value of each element is equal to the value of the corresponding element in the other array.

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. A 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. An IndexError is raised if a negative index points past the beginning of the array. See also Array#push, and Array#unshift.

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

When invoked with a block, yields all combinations of length n of elements from array and then returns array itself. The implementation makes no guarantees about the order in which the combinations are yielded.
When invoked without a block, returns an enumerator object instead.

Calls block for each element repeatedly n times or forever if none or nil is given.
If a non-positive number is given or the array is empty, does nothing.
Returns nil if the loop has finished without getting interrupted.

Deletes items from self that are equal to obj. Deletes all matched items.
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.

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

The first three forms set the selected elements of self (which may be the entire array) 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.

Returns a new array that is a one-dimensional flattening of this array (recursively). That is, for every element that is an array, extract its elements into the new array.
If the optional level argument determines the level of recursion to flatten.

Returns the first element of self and removes it (shifting all other elements down by one).
Returns nil if the array is empty.
If a number n is given, returns an array of the first n elements (or less) just like array.slice!(0, n) does.

Returns a new array created by sorting arr.
Comparisons for the sort will be done using the <=> operator or using an optional code block.
The block implements a comparison between a and b, returning -1, 0, or +1.

arr.sort! → arrarr.sort! {|a,b| block } → arr

Same as Array.sort, but modifies the receiver in place.
arr is effectively frozen while a sort is in progress.

Hashes (sometimes known as associative arrays, maps, or dictionaries) are similar to arrays in that they are indexed collections of object references. However, while you index arrays with integers, you can index a hash with objects of any type: strings, regular expressions, and so on. When you store a value in a hash, you actually supply two objects — the index, normally called the key, and the value. You can subsequently retrieve the value by indexing the hash with the same key. The values in a hash can be objects of any type.
a hash by default returns nil when indexed by a key it doesn’t contain. Sometimes you’llwant to change this default. For example, if you’re using a hash to count the number of times each key occurs, it’s convenient to have the default value be zero. This is easily done by specifying a default value when you create a new, empty hash.
Compared with arrays, hashes have one significant advantage: they can use any object as an index. However, they also have a significant disadvantage: their elements are not ordered, so you cannot easily use a hash as a stack or a queue. Also thes are not so efficient as arrays.
Hash does not support multiple keys with the same value

Element Assignment
– Associates the value given by aValueObject with the key given by aKeyObject. – aKeyObject should not have its value changed while it is in use as a key (a String passed as a key will be duplicated and frozen).

Deletes and returns a key-value pair from hsh whose key is equal to aKeyObject.
– If the key is not found, returns the default value.
– If the optional code block is given and the key is not found, pass in the key and return the result of block.

Returns a value from the hash for the given key.
If the key can't be found, there are several options:
– With no other arguments, it will raise an IndexError exception;
– if aDefObject is given, then that will be returned;
– if the optional code block is specified, then that will be run and its result returned.

The following example shows that an exception is raised if the key is not found and a default value is not supplied.h = { "a" => 100, "b" => 200 }
h.fetch("z")
produces:
prog.rb:2:in `fetch': key not found (IndexError)
from prog.rb:2

Rebuilds the hash based on the current hash values for each key.
– If values of key objects have changed since they were inserted, this method will reindex hsh.
– If Hash.rehash is called while an iterator is traversing the hash, an IndexError will be raised in the iterator.

Ranges may also be used as conditional expressions.
Range can be used as a kind of flip-flop, returning true when some event happens and then staying true until a second event occurs. This facility is normally used within loops.

Ranges as Intervals

Interval test: seeing if some value falls within the interval represented by the range.We do this using ===, the case equality operator.

Ranges as ConditionsFile.foreach("ordinal") do |line|
if (($. == 1) || line =~ /eig/) .. (($. == 3) || line =~ /nin/)
print line
end
end
produces:
first
second
third
eighth
ninth

Blocks and Iterators

Block

– A block may also return a value to the method. So you can use if yield(param) ...
– A Ruby block can be converted into an object of class Proc. These Proc objects can be stored in variables and passed between methods just like any other object. The code in the corresponding block can be executed at any time by sending the Proc object the message call.
– Ruby Proc objects remember the context in which they were created: the local variables, the current object and so on. When called, they recreate this context for the duration of their execution, even if that context has gone out of scope. Other languages call proc objects closures.

{ ... }

For single-line block

Iterator

First, a block may appear only in the source adjacent to a method call; the block is written starting on the same line as the method call’s last parameter (or the closing parenthesis of the parameter list). Second, the code in the block is not executed at the time it is encountered. Instead, Ruby remembers the context in which the block appears (the local variables, the current object, and so on) and then enters the method. This is where the magic starts.

{ |param1, param2, ...| ... }

Iterator-block with parameters. Can be invoked by yield(param1, param2, ...)

Proc objectdef times(n)
return Proc.new { |val| n * val }
end
#The block multiplies the method’s parameter, “n”, by another value,# which is passed to the block as a parameter. The following code# shows this in action.
double = times(2)
double.call(4) #--> 8
santa = times("Ho! ")
santa.call(3) #--> "Ho! Ho! Ho! "# Even though the parameter “n” is out of scope when the double and# santa objects are called, its value is still available to the closures.

yeld

yielddef call_block
puts "Start of method"
yield
yield
puts "End of method"
end
call_block { puts "In the block" }
produces:
Start of method
In the block
In the block
End of method

yieldclass File
def File.my_open(*args)
result = file = File.new(*args)
# If there's a block, pass in the file and close# the file when it returns
if block_given?
result = yield file
file.close
end
return result
end
end

You specify a target at the top of the case statement, and each when clause lists one or more comparisons.
As with if, case returns the value of the last expression executed, and you can use a then keyword if the expression is on the same line as the condition.
Case operates by comparing the target (the expression after the keyword case) with each of the comparison expressions after the when keywords. This test is done using comparison === target.

using caserating = case votes_cast
when 0...10 then Rating::SkipThisOne
when 10...50 then Rating::CouldDoBetter
else Rating::Rave
end

":" in place of the thenleap = case
when year % 400 == 0: true
when year % 100 == 0: false
else year % 4 == 0
end

case with regionkind = case year
when 1850..1889 then "Blues"
when 1890..1909 then "Ragtime"
when 1910..1929 then "New Orleans Jazz"
when 1930..1939 then "Swing"
when 1940..1950 then "Bebop"
else "Jazz"
end

case with patterncase line
when /title=(.*)/
puts "Title is #$1"
when /track=(.*)/
puts "Track is #$1"
when /artist=(.*)/
puts "Artist is #$1"
end

You can test the class of objectscase shape
when Square, Rectangle
# ...
when Circle
# ...
when Triangle
# ...
else
# ...
end

Loops[cycle]

Scope

The while, until, and for loops are built into the language and do not introduce new scope; previously existing locals can be used in the loop, and any new locals created will be available afterward.
The blocks used by iterators (such as loop and each) are a little different. Normally, the localvariables created in these blocks are not accessible outside the block. However, if at the time the block executes a local variable already exists with the same name as that of a variable in the block, the existing localvariable will be used in the block. Its value will therefore be available after the block finishes.
Note that the variable need not have been given a value in the outer scope: the Ruby interpreter just needs to have seen it.
A couple of suggestions to minimize the problems with local and block variables interfering:
• Keep your methods and blocks short. The fewer variables, the smaller the chance that they’ll clobber each other. It’s also easier to eyeball the code and check that you don’t have conflicting names.
• Use different naming schemes for local variables and block parameters. For example, you probably don’t want a local variable called “i,” but that might be perfectly acceptable as a block parameter.
In reality, this problem doesn’t arise in practice as often as you may think.

the Ruby interpreter just needs to have seen itif false
a = 1
end
3.times {|i| a = i }
a #-->2

while [is true] ...end

The while loop executes its body zero or more times as long as its condition is true.
You’ll come across a wrinkle when you use while and until as statement modifiers. If the statement they are modifying is a begin/end block, the code in the block will always execute at least one time, regardless of the value of the boolean expression.

... while [is true]

Shortcut

until [becomes true] ...end

The until loop is the opposite; it executes the body until the condition becomes true.

The loop iterator calls the associated block forever
The loop control constructs break, redo, and next let you alter the normal flow through a loop or iterator.

continue

next

Skips to the end of the loop, effectively starting the next iteration.

/break

break

Terminates the immediately enclosing loop; control resumes at the statement following the block.
Break and next can be given arguments. When used in conventional loops, it probably makes sense only to do this with break (as any value given to next is effectively lost). If a conventional loop doesn’t execute a break, its value is nil.

redo

Repeats the loop from the start, but without reevaluating the condition or fetching the next element (in an iterator).

retry

Restarts any kind of iterator loop.
Retry will reevaluate any arguments to the iterator before restarting it.

loop samplei=0
loop do
i += 1
next if i < 3
print i
break if i > 4
end
produces:
345

while samplewhile line = gets
next if line =~ /^\s*#/ # skip commentsbreak if line =~ /^END/ # stop at end# substitute stuff in backticks and try againredo if line.gsub!(/`(.*?)`/) { eval($1) }
# process line ...
end

retryfor i in 1..100
print "Now at #{i}. Restart? "
retry if gets =~ /^y/i
end

You can use for to iterate over any object that responds to the method each, such as an Array or a Range.
When you write so, Ruby translates it into something like
songlist.each do |song|
song.play
end
The only difference between the for loop and the each form is the scope of local variables that are defined in the body

with arrayfor i in File.open("ordinal").find_all {|line| line =~ /d$/}
print i.chomp, " "
end
produces: second third

As long as your class defines a sensible each method, you can use a for loop to traverseits objects.class Periods
def each
yield "Classical"
yield "Jazz"
yield "Rock"
end
end
periods = Periods.new
for genre in periods
print genre, " "
end
produces:
Classical Jazz Rock

sleep

sleep, wait

sleep(num_secs)

sleep, wait

sleep function tell a Ruby program to wait an arbitrary amount of time before moving on to the next line of codesleep(5)

Classes, Modules, Mixins, and Multiple Inheritance

class ClassName ...end

Class definition. First letter of ClassName must be in uppercase

class SubClass < ParentClass ...end

Class inheritance

function, procedure, sub

def instance_method(param, ...) ...end

Instance Method

def method(arg1="Val1", arg2="Val2", ...)

Default values for a method’s arguments

def instance_method(param1, *args) ...end

– Gets parameters for transferring
– But what if you want to pass in a variable number of arguments or want to capture multiplearguments into a single parameter? Placing an asterisk before the name of the parameter after the “normal” parameters does just that. Parameter is prefixedwith an asterisk, so all the remaining arguments are bundled into a new Array, which is then assigned to that parameter.

block argument, pass block

def method(arg1, &block)

If the last parameter in a method definition is prefixed with an ampersand, any associatedblock is converted to a Proc object, and that object is assigned to the parameter and can be called by .call() method.

class method

def ClassName.class_method(param, ...) ...end

ClassMethod. Sometimes a class needs to provide methods that work without being tied to any particular object.
– For class and module methods, the receiver will be the class or module name.

constructor

def initialize(param, ...) ...end

Calls for new objectinitialization when you use Class.new(param)

def initialize(label, &action)

If the last parameter in a method definition is prefixed with an ampersand Ruby looks for a code block whenever that method is called. That code block is converted to an object of class Proc and assigned to the parameter.

.method!

Method is “dangerous,” or modify the receiver.

.method?

Method acts as querie.

self

If you omit the receiver, it defaults to self, the current object.
This defaulting mechanism is how Ruby implements privatemethods.

When you invoke super with no arguments, Ruby sends a message to the parent of the current object, asking it to invoke a method of the same name as the method invoking super. It passes this method the parameters that were passed to the originally invoked method.

– You can omit the parentheses around the argument list when calling a method.2 However, except in the simplest cases we don’t recommend this – some subtle problems can trip you up.3 Our rule is simple: if you have any doubt, use parentheses.
– You get a warning if you put a space between a method name and an open parenthesis.
– The return value of a method is the value of the last expression executed or the result of an explicit return expression. The value of a return is the value of its argument(s). It is idiomatic Ruby to omit the return if it isn’t needed.
– Every called method returns a value (although no rule says you have to use that value).
– In particular, you must use parentheses on a method call that is itself a parameter to another method call (unless it is the last parameter).
– If you give return multiple parameters, the method returns them in an array. You can use parallel assignment to collect this return value.

obj.method("param1", *[param2, param3])

When you call a method, you can explode an array, so that each of its members is taken as a separate parameter. Do this by prefixing the array argument (which must follow all the regular arguments) with an asterisk.

– You can place key => value pairs in an argument list, as long as they follow any normal arguments and precede any array and block arguments. All these pairs will be collected into a single hash and passed as one argument to the method. No braces are needed.
– In idiomatic Ruby you’d probably use symbols rather than strings, as symbols make it clearer that you’re referring to the name of something.

Accessor methods. The construct :artist is an expression that returns a Symbol object corresponding to artist. You can think of :artist as meaning the name of the variable artist, and plain artist as meaning the value of the variable. In this example, we named the accessor methods name, artist, and duration. The corresponding instance variables, @name, @artist, and @duration, will be created automatically.

Inheritance, multiple inheritance

Ruby offers an interesting and powerful compromise, giving you the simplicity of single inheritance and the power of multiple inheritance. A Ruby class has only one direct parent, so Ruby is a singleinheritance language. However, Ruby classes can include the functionality of any number of mixins (a mixin is like a partial class definition). This provides a controlled multiple-inheritance-like capability with none of the drawbacks.

private methods

Methodprotection

Ruby gives you three levels of protection.
– Public methods can be called by anyone — no access control is enforced. Methods are public by default (except for initialize, which is always private).
– Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
– Private methods cannot be called with an explicit receiver — the receiver is always self. This means that private methods can be called only in the context of the current object; you can’t invoke another object’s private methods.
– The difference between “protected” and “private” is fairly subtle and is different in Ruby than in most common OO languages. If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object — it is never possible to access another object’s private methods directly, even if the object is of the same class as the caller
– Ruby differs from other OO languages in another important way. Access control is determined dynamically, as the program runs, not statically. You will get an access violation only when the code attempts to execute the restricted method.
– Private methods may not be called with a receiver, so they must be methods available in the current object.

Important

– Classes and modules are never closed. You can add to and alter all classes and modules (including those built in to Ruby itself). Just open a class definition for an existing class, and the new contents you specify will be added to whatever’s there.
– If you don’t specify a parent when defining a class, Ruby supplies class Object as a default. This means that all objects have Object as an ancestor and that Object’s instance methods are available to every object in Ruby. to_s is one of more than 35 instance methods in class Object.

selfself.class #-> Object
self.frozen?#-> false
frozen? #-> false
self.id#-> 967900
id #-> 967900# we could not call the method# class without a receiver. This is because class is also a keyword in Ruby

Using Accessors within a Classclass BrokenAmplifier
attr_accessor :left_channel, :right_channel
def volume=(vol)
left_channel = self.right_channel = vol
end
end
ba = BrokenAmplifier.new
ba.left_channel = ba.right_channel = 99
ba.volume = 5
ba.left_channel #-> 99
ba.right_channel #-> 5# We forgot to put “self.” in front of the assignment to left_channel,# so Ruby stored the new value in a local variable of method volume=;# the object’s attribute never got updated. This can be a tricky bug to# track down.

Adding functionality with a mixinmodule Enumerable
def find
each { |val| return val if yield(val) }
end
end

includeclass Array
include Enumerable
end

methodprotectionclass MyClass
def method1 # default is '=public'#...
end
protected# subsequent methods will be '=protected'
def method2 # will be 'protected'#...
end
private# subsequent methods will be '=private'
def method3 # will be 'private'#...
end
public# subsequent methods will be '=public'
def method4 # and this will be 'public'#...
end
end
#or...
class MyClass
def method1
end
# ... and so onpublic :method1, :method4 #=publicprotected :method2 #=protectedprivate :method3 #=private
end

module ModuleName ...end

– Modules provide a namespace and prevent name clashes.
– Modules implement the mixin facility.
– Constants and class methods may be placed in a module without worrying about their names conflicting with constants and methods

includes

include ModuleName

– The Ruby include statement simply makes a reference to a named module. If that module is in a separate file, you must use require (or its less commonly used cousin, load) to drag that file in before using include.
– Ruby include does not simply copy the module’s instance methods into the class. Instead, it makes a reference from the class to the included module. If multiple classes include that module, they’ll all point to the same thing. If you change the definition of a method within a module, even while your program is running, all classes that include that module will exhibit the new behavior.
– One of the other questions folks ask about mixins is, how is method lookup handled? In particular, what happens if methods with the same name are defined in a class, in that class’s parent class, and in a mixin included into the class?
The answer is that Ruby looks first in the immediate class of an object, then in the mixins included into that class, and then in superclasses and their mixins. If a class has multiple modules mixed in, the last one included is searched first.

load 'filename.rb'

– The load method includes the named Ruby source file every time the method is executed.
– Accept relative and absolute paths. If given a relative path (or just a plain name), they’ll search every directory in the current load path ($:) for the file.
– Local variables in a loaded or required file are not propagated to the scope that loads or requires them.
– Since load will include the source unconditionally, you can use it to reload a source file that may have changed since the program began.
– For a less contrived use of this facility, consider a Web application that reloads components while running. This allows it to update itself on the fly; it needn’t be restarted for new version of the software to be integrated. This is one of the many benefits of using a dynamic language such as Ruby.

require 'filename'

– Loads any given file only once.
– Require has additional functionality: it can load shared binary libraries.
– Accept relative and absolute paths. If given a relative path (or just a plain name), they’ll search every directory in the current load path ($:) for the file.
– Local variables in a loaded or required file are not propagated to the scope that loads or requires them.
– What may not be obvious is that require is an executable statement — it may be inside an if statement, or it may include a string that was just built. The search path can be altered at runtime as well. Just add the directory you want to the array $:.

Local variables are not propagated to the scope that loads or requires them#included.rb:
a = 1
def b
2
end
#include it into another file:
a = "cat"
b = "dog"
require 'included'
a #-> "cat"
b #-> "dog"
b() #-> 2

::class Module
@@docs = Hash.new(nil)
def doc(str)
@@docs[self.name] = str
end
def Module::doc(aClass)
# If we're passed a class or module, convert to string# ('<=' for classes checks for same class or subtype)
aClass = aClass.name if aClass.type <= Module
@@docs[aClass] || "No documentation for #{aClass}"
end
end
class Example
doc "This is a sample documentation string"
# .. rest of class
end
module Another
doc <<-edoc
And this is a documentation string
in a module
edoc
# rest of module
end
puts Module::doc(Example)
puts Module::doc("Another")
produces: This is a sample documentation string
And this is a documentation string
in a module

Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string.

obj.to_s

Returns a string containing a representation of object.
For array returns arr.join.
For fixnum – decimal representation.
For float – as well as a fixed or exponential form of the number, the call may return "NaN"', "Infinity", and "-Infinity".

Makes duplicate object and returns the reference.
Produces a shallow copy of obj – the instance variables of obj are copied, but not the objects they reference.
dup copies the tainted state of obj.
In general, clone and dup may have different semantics in descendent classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendent object to create the new instance.

There is an interesting trick with extend. If you use it within a classdefinition, the module's methods become classmethods.module Humor
def tickle
"hee, hee!"
end
end
class Grouchy
include Humor
extend Humor
end
Grouchy.tickle #-> "hee, hee!"
a = Grouchy.new
a.tickle #-> "hee, hee!"

– Integers can be any length (up to a maximum determined by the amount of free memory on your system).
– Integers within a certain range (normally -2^30 to 2^30-1 or -2^62 to 2^62-1) are held internally in binary form and are objects of class Fixnum.
– Integers outside this range are stored in objects of class Bignum (currently implemented as a variable-length set of short integers). This process is transparent, and Ruby automatically manages the conversion back and forth.
– You write integers using an optional leading sign, an optional base indicator (0 for octal, 0d for decimal [the default], 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string (some folks use them in place of commas in larger numbers).
– Control characters can be generated using ?\C-x and ?\c-x (the control version of x is x & 0x9f). Metacharacters (x | 0x80) can be generated using ?\M-x. The combination of meta and control is generated using and ?\M-\C-x. You can get the integer value of a backslash character using the sequence ?\\.
– A numeric literal with a decimal point and/or an exponent is turned into a Float object, corresponding to the native architecture's double data type. You must both precede and follow the decimal point with a digit (if you write 1.0e3 as 1.e3, Ruby will try to invoke the method e3 in class Fixnum).
– Strings that contain just digits are not automatically converted into numbers when used in expressions.

Returns a string containing a representation of self.
As well as a fixed or exponential form of the number, the call may return "NaN", "Infinity", and "-Infinity".

Bignum

String class[String, strings, working with strings]

#, Substitutions

"...#{expr}...#$globalExp...#@classExp...#@@const..."

Double-quoted strings support a boatload more escape sequences.
The most common is probably \n, the newline character.
In addition, you can substitute the value of any Ruby code into a string using the sequence #{expr}.
If the code is just a global variable, a class variable, or an instance variable, you can omit the braces.

Substitutes"Seconds/day: #{24*60*60}" #-> Seconds/day: 86400
"#{'Ho! '*3}Merry Christmas!" #-> Ho! Ho! Ho! Merry Christmas!
"This is line #$." #-> This is line 3
puts "now is #{ def the(a)
'the ' + a
end
the('time')
} for all good coders..."
produces:
now is the time for all good coders...

quoting, single-quoted

%q and %Q

Start delimited single- and double-quoted strings (you can think of %q as a thin quote ', and %Q as a thick quote ").
– The character following the q or Q is the delimiter. If it is an opening bracket "[", brace "{", parenthesis "(", or less-than sign "<", the string is read until the matching close symbol is found. Otherwise the string is read until the next occurrence of the same delimiter.
– The delimiter can be any nonalphanumeric or nonmultibyte character.

Format
Uses str as a format specification, and returns the result of applying it to arg.
– If the format specification contains more than one substitution, then arg must be an Array containing the values to be substituted.
– See Kernel.sprintf for details of the format string.

Comparison
Returns -1 if str is less than, 0 if str is equal to, and +1 if str is greater than String.
– If the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered greater than the shorter one.
– If the variable $= is false, the comparison is based on comparing the binary values of each character in the string.
– If $= is not false, then the comparison is case insensitive. [The locale is ignored when case-insensitive comparisons are performed, so "\"o" will not match "\"O".]
– <=> is the basis for the methods <, <=, >, >=, and between?, included from module Comparable.

Equality
– If Object is not a String, returns false. Otherwise, returns true if str <=> Object returns zero.
– The method String.== does not use Comparable.==

str =~ Object → Fixnum or nil

Match
– If Object is a Regexp or a String, uses it as a pattern to match against str.
– Returns the position the match starts, or nil if there is no match.
– Otherwise, invokes Object.=~, passing str as an argument.
– The default =~ in Object returns false.

Element Reference
– If passed a single Fixnum, returns the code of the character at that position.
– If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second.
– If given a range, a substring containing characters at offsets given by the range is returned.
– In all three cases, if an offset is negative, it is counted from the end of str.
– Returns nil if the initial offset falls outside the string, the length is negative, or the beginning of the range is greater than the end.
– If a Regexp is supplied, the matching portion of str is returned.
– If a String is given, that string is returned if it occurs in str.
– In both cases, nil is returned if there is no match.

Element Assignment
– Replaces some or all of the content of str.
– The portion of the string affected is determined using the same criteria as String.[]
– If the replacement string is not the same length as the text it is replacing, the string will be adjusted accordingly.
– 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.

Source: ellho.net/solutions/ruby-string-functions-in-ruby.html
To change case:
capitalize - first character to upper, rest to lower
downcase - all to lower case
swapcase - changes the case of all letters
upcase - all to upper case
To rejustify:
center - add white space padding to center string
ljust - pads string, left justified
rjust - pads string, right justified
To trim:
chop - remove last character
chomp - remove trailing line separators
squeeze - reduces successive equal characters to singles
strip - deletes leading and trailing white space
To examine:
count - return a count of matches
empty? - returns true if empty
include? - is a specified target string present in the source?
index - return the position of one string in another
length or size - return the length of a string
rindex - returns the last position of one string in another
slice - returns a partial string
To encode and alter:
crypt - password encryption
delete - delete an intersection
dump - adds extra \ characters to escape specials
hex - takes string as hex digits and returns number
next or succ - successive or next string (eg ba → bb)
oct - take string as octal digits and returns number
replace - replace one string with another
reverse - turns the string around
slice! - DELETES a partial string and returns the part deleted
split - returns an array of partial strings exploded at separator
sum - returns a checksum of the string
to_f and to_i - return string converted to float and integer
tr - to map all occurrences of specified char(s) to other char(s)
tr_s - as tr, then squeeze out resultant duplicates
unpack - to extract from a string into an array using a template
To iterate:
each - process each character in turn
each_line - process each line in a string
each_byte - process each byte in turn
upto - iterate through successive strings (see "next" above)

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.

Returns a copy of str with all uppercase letters replaced with their lowercase counterparts.
– The operation is locale insensitive
– Only characters "A" to "Z" are affected.

str.downcase! → str or nil

Downcases the contents of str, returning nil if no changes were made.

downcase"hEllO".downcase #-> "hello"

to uppercase

str.upcase → String

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.

str.upcase! → str or nil

Upcases the contents of str, returning nil if no changes were made.

upcase"hEllO".upcase #-> "HELLO"

str.center( Integer ) → String

If Integer is greater than the length of str
– returns a new String of length Integer with str centered between spaces
– otherwise, returns str.

center"hello".center(4) #-> "hello"
"hello".center(20) #-> " hello "

str.ljust( Integer ) → String

If Integer is greater than the length of str, returns a new String of length Integer with str left justified and space padded; otherwise, returns str.

ljust"hello".ljust(4) #-> "hello"
"hello".ljust(20) #-> "hello "

str.rjust( Integer ) → String

If Integer is greater than the length of str, returns a new String of length Integer with str right justified and space padded; otherwise, returns str.

rjust"hello".rjust(4) #-> "hello"
"hello".rjust(20) #-> " hello"

str.dump → String

Produces a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped.

str.crypt( String ) → String

Applies a one-way cryptographic hash to str by invoking the standard library function crypt.
– The argument is the salt string, which should be two characters long, each character drawn from [a-zA-Z0-9./].

Returns the index of the first occurrence of the given substring, character, or pattern in str.
Returns nil if not found.
If the second parameter is present, it specifies the position in the string to begin the search.

Returns the index of the last occurrence of the given substring, character, or pattern in str.
– Returns nil if not found.
– If the second parameter is present, it specifies the position in the string to end the search characters beyond this point will not be considered.

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 '[visible space]' were specified.
– If the limit parameter is omitted, trailing null fields are supressed.
– 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 supressed.

Returns a new string with the characters from str in reverse order.
"reverse!" reverses str in place.

reverseputs "abc".reverse #-> cba

reverse!s = "abc"
s.reverse!
puts s

integer, string to integer

str.to_i → Integer

Returns the result of interpreting leading characters in str as a decimal integer.
Extraneous characters past the end of a valid number are ignored.
If there is not a valid number at the start of str, 0 is returned.
The method never raises an exception.

Returns a new String with the last character removed.
If the string ends with \r\n, both characters are removed.
Applying chop to an empty string returns an empty string.
String.chomp is often a safer alternative, as it leaves the string unchanged if it doesn't end in a record separator.

str.chop! → str or nil

Processes str as for String.chop, returning str, or nil if str is the empty string.

Each String parameter defines a set of characters to count.
The intersection of these sets defines the characters to count in str.
Any String that starts with a caret (^) is negated.
The sequence c1-c2 means all characters between c1 and c2.

Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block.
– If a zero-length record separator is supplied, the string is split on \n characters, except that multiple successive newlines are appended together.

Returns a copy of str with the first occurrence of pattern replaced with either replacement or the value of the block.
– If the string form of the method is used, special variables such as $& will not be useful, as substitution into the string occurs before the pattern match starts.
However, the sequences \1, \2 may be used.
– In the block form, the current match is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

Returns a copy of str with all occurrences of pattern replaced with either replacement or the value of the block.
– If a string is used as the replacement, special variables from the match (such as $& and $1) cannot be substituted into it, as substitution into the string occurs before the pattern match starts. However, the sequences \1, \2, and so on may be used to interpolate successive groups in the match.
– In the block form, the current match is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately.
– The value returned by the block will be substituted for the match on each call.
– The result inherits any tainting in the original string or any supplied replacement string.

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.

Builds a set of characters from the String 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.

str.squeeze!( [ String ]* ) → str or nil

Squeezes str in place, returning either str, or nil if no changes were made.

Returns the successor to str.
– The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set's collating sequence.
– If the increment generates a "carry," the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.

Returns a basic n-bitchecksum of the characters in str, where n is the optional parameter, defaulting to 16. The result is simply the sum of the binary value of each character in str modulo 2^n - 1.
– This is not a particularly good checksum.

swap case

str.swapcase → String

Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase.

str.swapcase! → str or nil

Equivalent to String.swapcase, but modifies the receiver in place, returning str, or nil if no changes were made.

Returns the result of interpreting leading characters in str as a floatingpoint number.
– Extraneous characters past the end of a valid number are ignored.
– If there is not a valid number at the start of str, 0.0 is returned.
– The method never raises an exception.

Synonym for String.to_s.
to_str is used by methods such as String#concat to convert their arguments to a string.
– Unlike to_s, which is supported by almost all classes, to_str is normally implemented only by those classes that act like strings. Of the built-in classes, only Exception and String implement to_str.

.tr, transliteration

str.tr( fromString, toString ) → String

Returns a copy of str with the characters in fromString replaced by the corresponding characters in toString.
– If toString is shorter than fromString, it is padded with its last character.
– Both strings may use the c1-c2 notation to denote ranges of characters, and fromString may start with a ^, which denotes all characters except those listed.

str.tr!( fromString, toString ) → str or nil

Translates str in place, using the same rules as String.tr.
– Returns str, or nil if no changes were made.

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.
– 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.
– See also Array.pack.
A String with trailing nulls and spaces removed. → String
a String. → String
B Extract bits from each character (msb first) → String
b Extract bits from each character (lsb first) → String
C Extract a character as an unsigned integer → Fixnum
c Extract a character as an integer → Fixnum
d Treat sizeof(double) characters as a native double → Float
E Treat sizeof(double) characters as a double in little-endian byte order → Float
e Treat sizeof(float) characters as a float in little-endian byte order → Float
f Treat sizeof(float) characters as a native float → Float
G Treat sizeof(double) characters as a double in network byte order → Float
g Treat sizeof(float) characters as a float in network byte order → Float
H Extract hex nibbles from each character (most significant first) → String
h Extract hex nibbles from each character (least significant first) → String
I Treat sizeof(int)[1] successive characters as an unsigned native integer → Integer
i Treat sizeof(int)[1] successive characters as a signed native integer → Integer
L Treat four[1] successive characters as an unsigned native long integer → Integer
l Treat four[1] successive characters as a signed native long integer → Integer
M Extract a quoted-printable string → String
m Extract a base64 encoded string → String
N Treat four characters as an unsigned long in network byte order → Fixnum
n Treat two characters as an unsigned short in network byte order → Fixnum
P Treat sizeof(char *) characters as a pointer, and return len characters from the referenced location → String
p Treat sizeof(char *) characters as a pointer to a null-terminated string → String
S Treat two[1] successive characters as an unsigned short in native byte order → Fixnum
s Treat two[1] successive characters as a signed short in native byte order → Fixnum
U Extract UTF-8 characters as unsigned integers → Integer
u Extract a UU-encoded string → String
V Treat four characters as an unsigned long in little-endian byte order → Fixnum
v Treat two characters as an unsigned short in little-endian byte order → Fixnum
X Skip backward one character
x Skip forward one character
Z String with trailing nulls removed → String
@ Skip to the offset given by the length argument
[1] – May be modified by appending "_" to the directive.

Creates a time based on given values, interpreted as UTC (GMT).
The year must be specified.
Other values default to the minimum value for that field (and may be nil or omitted).
Months may be specified by numbers from 1 to 12, or by the three-letter English month names.
Hours are specified on a 24-hour clock (0..23).
Raises an ArgumentError if any values are out of range.
Will also accept ten arguments in the order output by Time.to_a.

Returns the second of the minute (0..60) for time.
– Yes, seconds really can range from zero to 60. This allows the system to inject leap seconds every now and then to correct for the fact that years are not really a convenient number of hours long.

sect = Time.now #-> Sun Nov 25 23:50:41 CST 2001
t.sec #-> 41

time.min → Fixnum

Returns the minute of the hour (0..59) for time.

mint = Time.now #-> Sun Nov 25 23:50:41 CST 2001
t.min #-> 50

time.hour → Fixnum

Returns the hour of the day (0..23) for time.

hourt = Time.now #-> Sun Nov 25 23:50:41 CST 2001
t.hour #-> 23

time.day → Fixnumtime.mday → Fixnum (Synonym)

Returns the day of the month (1..n) for time.

dayt = Time.now #-> Sun Nov 25 23:50:41 CST 2001
t.day #-> 25

day of week, week day, weekday

time.wday → Fixnum

Returns an integer representing the day of the week, 0..6, with Sunday == 0.

Formats time according to the directives in the given format string.
Any text not listed as a directive will be passed through to the output string.

formatted

DirectivesFormat Meaning

%a – The abbreviatedweekday name ("Sun")
%A – The fullweekday name ("Sunday")
%b – The abbreviatedmonth name ("Jan")
%B – The fullmonth name ("January")
%c – The preferred local date and time representation%d – Day of the month (01..31)
%H – Hour of the day, 24-hourclock (00..23)
%I – Hour of the day, 12-hour clock (01..12)
%j – Day of the year (001..366)
%m – Month of the year (01..12)
%M – Minute of the hour (00..59)
%p – Meridian indicator ("AM" or "PM")
%S – Second of the minute (00..60)
%U – Weeknumber of the current year, starting with the first Sunday as the first day of the first week (00..53)
%W – Weeknumber of the current year, starting with the first Monday as the first day of the first week (00..53)
%w – Day of the week (Sunday is 0, 0..6)
%x – Preferred representation for the date alone, no time%X – Preferred representation for the time alone, no date%y – Yearwithout a century (00..99)
%Y – Yearwith century (2011)
%Z – Time zone name
%% – Literal "%" character

Returns a ten-element Array of values for time: {[ sec, min, hour, day, month, year, wday, yday, isdst, zone ]}.
See the individual methods for an explanation of the valid ranges of each value.
The ten elements can be passed directly to Time.utc or Time.local to create a new Time.

Returns a string which represents the time as rfc1123-date of HTTP-date defined by RFC 2616:
day-of-week, DD month-name CCYY hh:mm:ss GMT
- Result is always UTC (GMT)

httpdateTime.now.httpdate#-> Tue, 08 Jan 2008 07:49:30 GMT

Date[datetime]

Abbreviations used describing dates

cwday – An ISO 8601 calendar weekday. 1 is Monday, 7 is Sunday.
cweek – An ISO 8601 calendar week. Week 1 is the week containing the first Thursday (or equivalently the week that contains January 4th).
cwyear – An ISO 8601 calendar-week-based year. May be different from year, as it rolls forward only on a Monday.
jd – The Julian day number - the number of days since January 1st, 4713 BCE.
mday – The day of the month (1..31).
mjd – A modified Julian day number.
mon – The month of the year (1..12).
sg – The start of the Gregorian correction: Date::ITALY (the default) for 1582, Date::ENGLAND for 1752, or JULIAN, meaning no correction. You may also provide an arbitrary Julian day number for this parameter, in which case the correction will start from this date.
wday – The day of the week (0 is Sunday).
week – The week number into a year (1..53).
yday – The day into the year (1..366).
year – A year (1966, 2001, and the like).

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use.
The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained.
Binding objects can be created using Kernel.binding, and are made available to the callback of Kernel.set_trace_func.
Binding objects have no class-specific methods.

– The name of the top-level Ruby program being executed.
– Typically this will be the program's filename. On some operating systems, assigning to this variable will change the name of the process reported (for example) by the ps(1) command.

args, argv, command line parameters

$* (Array)

– An array of strings containing the command-lineoptions from the invocation of the program.
– Options used by the Ruby interpreter will have been removed.
– r/o

$" (Array)

– An array containing the filenames of modulesloaded by require
– r/o

$$ (Fixnum)

– The processnumber of the program being executed
– r/o

$? (Fixnum)

– The exit status of the last child process to terminate
– r/o, thread

$: (Array)$-I – Synonym$LOAD_PATH – Synonym

– An array of strings, where each string specifies a directory to be searched for Ruby scripts and binary extensions used by the load and require methods.
– The initial value is the value of the arguments passed via the -I command-line option, followed by an installation-defined standard librarylocation, followed by the current directory (".").
– This variable may be set from within a program to alter the default search path; typically, programs use $: << dir to append dir to the path
– r/o

$-a (Object)

– True if the -a option is specified on the command line
– r/o

$DEBUG (Object)$-d – Synonym

– Set to true if the -d command-line option is specified.

__FILE__ (String)

– The name of the current source file
– r/o

$F (Array)

– The array that receives the split input line if the -a command-line option is used.

$FILENAME (String)

– The name of the current input file.
– Equivalent to $<.filename
– r/o

$-i (String)

– If in-place edit mode is enabled (perhaps using the -i command-line option), $-i holds the extension used when creating the backup file.
– If you set a value into $-i, enables in-place edit mode.

$-K (String)

– Sets the multibyte coding system for strings and regular expressions.
– Equivalent to the -K command-line option.

$-l (Object)

– Set to true if the -l option (which enables line-end processing) is present on the command line.
– r/o

__LINE__ (String)

– The current line number in the source file
– r/o

$-p (Object)

– Set to true if the -p option (which puts an implicit while gets ... end loop around your program) is present on the command line.
– r/o

$SAFE (Fixnum)

– The current safe level.
– This variable's value may never be reduced by assignment.

$VERBOSE (Object)$-v – Synonym$-w – Synonym

– Set to true if the -v, --version, or -w option is specified on the command line.
– Setting this option to true causes the interpreter and some library routines to report additional information.

Input/Output Variables[IO]

$/ (String)$-0 – Synonym

The input recordseparator (newline by default).
This is the value that routines such as Kernel#gets use to determine record boundaries.
– If set to nil, gets will read the entire file.

$\ (String)

The string appended to the output of every call to methods such as Kernel#print and IO#write.
– The default value is nil.

$, (String)

The separator string output between the parameters to methods such as Kernel#print and Array#join.
– Defaults to nil, which adds no text.

$. (Fixnum)

The number of the last line read from the current input file.

$; (String)$-F (String) – Synonym

The default separator pattern used by String#split.
– May be set from the command line using the -Fflag.

cmd, stdin

$< (Object)

An object that provides access to the concatenation of the contents of all the files given as command-linearguments, or $stdin (in the case where there are no arguments).
– $< supports methods similar to a File object: binmode, close, closed?, each, each_byte, each_line, eof, eof?, file, filename, fileno, getc, gets, lineno, lineno=, pos, pos=, read, readchar, readline, readlines, rewind, seek, skip, tell, to_a, to_i, to_io, to_s, along with the methods in Enumerable.
– The method file returns a File object for the file currently being read.
– This may change as $< reads through the files on the command line.

defout, stdout

$> (IO)$defout (IO) – Synonym

The destination of output for Kernel#print and Kernel#printf.
– The default value is $stdout.

$_ (String)

The last line read by Kernel#gets or Kernel#readline.
– Many string-related functions in the Kernel module operate on $_ by default.
– The variable is local to the current scope.

stderr

$stderr (IO)

The current standard error output.

stdin

$stdin (IO)

The current standardinput.

stdout

$stdout (IO)

The current standardoutput.

Standard Objects

ARGF (Object)

A synonym for $<.

ARGV (Array)

A synonym for $*.

ENV (Object)

– A hash-like object containing the program's environmentvariables.
– An instance of class Object, ENV implements the full set of Hash methods. Used to query and set the value of an environment variable, as in ENV["PATH"] and ENV['term']="ansi".

File.open("filename", "r|w|rw") do |file| while line = file.gets ... end # ... process the fileend

The method File.open also opens a file. In regular use, it behaves just like File.new. However, if a block is associated with the call, open behaves differently. Instead of returning a new File object, it invokes the block, passing the newly opened File as a parameter. When the block exits, the file is automatically closed.
Returns nil

file read, read file

ReadfileFile.open("testfile") do |file|
while line = file.gets
puts line
end
end

[~]# ruby programWithGets.rb testfile

We can also pass in one or more filenames on the commandline, in which case gets will read from each in turn.

read line

gets read from file# copy.rb:
while line = gets
puts line
end
# testfile
This is line one
This is line two
This is line three
# [~]# ruby copy.rb testfileproduces:
This is line one
This is line two
This is line three

file, file.gets, reading

.gets

Invokes a block with the next 8-bit byte from the IO object

each line, eachline

.each_line.each_line("string separator")

– Each_line calls the block with each line from the file.
– You can pass each_line any sequence of characters as a line separator, and it will break up the input accordingly, returning the line ending at the end of each line of data.

Objects of class Dir are directory streams representing directories in the underlying file system. They provide a variety of ways to list directories and their contents.
Official documentation
ruby-doc.org/core-1.8.7/Dir.html

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

Changes the current working directory of the process to the given string.
When called without an argument, changes the directory to the value of the environment variable HOME, or LOGDIR. SystemCallError (probably Errno::ENOENT) if the target directory does not exist.
If a block is given, it is passed the name of the new current directory, and the block is executed with that as the current directory. The original working directory is restored when the block exits. The return value of chdir is the value of the block. chdir blocks can be nested, but in a multi-threaded program an error will be raised if a thread attempts to open a chdir block while another thread has one open.

Returns the filenames found by expanding pattern which is an Array of the patterns or the pattern String, either as an array or as parameters to the block.
Note that this pattern is not a regexp (it’s closer to a shell glob). See File::fnmatch for the meaning of the flags parameter. Note that case sensitivity depends on your system (so File::FNM_CASEFOLD is ignored)
Pattern symbols:
* Matches any file. Can be restricted by other values in the glob. * will match all files; c* will match all files beginning with c; *c will match all files ending with c; and c will match all files that have c in them (including at the beginning or end). Equivalent to / .* /x in regexp.
** Matches subdirectories recursively.
? Matches any one character. Equivalent to /.{1}/ in regexp.
[charSet] Matches any one character in set. Behaves exactly like character sets in Regexp, including set negation ([^a-z]).
{p,q} Matches either literal p or literal q. Matching literals may be more than one character in length. More than two literals may be specified. Equivalent to pattern alternation in regexp.
{opt, opt, ...} Matches any one of the optional strings.
[missed in docs?] Escapes the next metacharacter.

Makes a new directory named by string, with permissions specified by the optional integer parameter. The permissions may be modified by the value of File::umask, and are ignored on NT.
Raises a SystemCallError if the directory cannot be created.
See also the discussion of permissions in the class documentation for File.

Writes the given object to ios.
The stream must be opened for writing.
If the output record separator ($\) is not nil, it will be appended to the output.
If no arguments are given, prints $_.
Objects that aren't strings will be converted by calling their to_s method. Returns nil.

Writes the given objects to ios as with IO.print.
Writes a record separator (typically a newline) after any that do not already end with a newline sequence.
If called with an array argument, writes each element on a new line.
If called without arguments, outputs a single record separator.

p

Is shortcut for "puts obj.inspect"

puts$stdout.puts("first line", "second line")
puts
puts 777, 'end'
p "p for puts"
produces:
first line
second line
777
end
p for puts

– When an exception is raised, and independent of any subsequent exception handling, Ruby places a reference to the associated Exception object into the global variable $!
– You can have multiple rescue clauses in a begin block, and each rescue clause can specify multiple exceptions to catch.
– At the end of each rescue clause you can give Ruby the name of a local variable to receive the matched exception. Many people find this more readable than using $! all over the place.
– If no rescue clause matches, or if an exception is raised outside a begin/end block, Ruby moves up the stack and looks for an exception handler in the caller, then in the caller’s caller, and so on.

– Raise with no parameters, which reraises the exception in $!. This is a useful technique, as it allows you to write code that filters exceptions, passing on those you can’t handle to higher levels.
– The first form simply reraises the current exception (or a RuntimeError if there is no current exception). This is used in exception handlers that need to intercept an exception before passing it on.
– The second form creates a new RuntimeError exception, setting its message to the given string. This exception is then raised up the call stack.
– The third formuses the first argument to create an exception and then sets the associated message to the second argument and the stack trace to the third argument. Typically the first argument will be either the name of a class in the Exception hierarchy or a reference to an object instance of one of these classes.

retry

Use the retry statement within a rescue clause to repeat the entire begin/end block.

– Catch defines a block that is labeled with the given name (which may be a Symbol or a String). The block is executed normally until a throw is encountered.
– When Ruby encounters a throw, it zips back up the call stack looking for a catch block with a matching symbol. When it finds it, Ruby unwinds the stack to that point and terminates the block.

How to break from nested loopsbank.branches do |branch|
catch :missingyear do #:missingyear acts as a label
branch.employees.each do |employee|
(2000..2011).each do |year|
throw :missingyear unless something #break out of two loops
end
end
end #You end up here if :missingyear is thrown
end

Constructs a new regular expression from pattern, which can be either a String or a Regexp (in which case that regexp's options are not propagated).
– If options is a Fixnum, it should be one or more of the constants or-ed together
Regexp::EXTENDED – Ignore spaces and newlines
Regexp::IGNORECASE – Matches are caseinsensitive
Regexp::POSIXLINE – Newlines treated as any other character
– Otherwise, if options is not nil, the regexp will be caseinsensitive.
– Regular expressions are objects of type Regexp
– The lang parameter enables multibyte support for the regexp:
'n', 'N' = none
'e', 'E' = EUC
's', 'S' = SJIS
'u', 'U' = UTF-8

A regular expression may include one or more options that modify the way the pattern matches strings.
– If you're using literals to create the Regexp object, then the options comprise one or more characters placed immediately after the terminator.
– If you're using Regexp.new, the options are constants used as the second parameter of the constructor.

/i, case sensitivity

/.../i

CaseInsensitive.
The pattern match will ignore the case of letters in the pattern and string.
Matches are also case-insensitive if the global variable $= is set.

/o

/.../o

Substitute Once.
Any #{...} substitutions in a particular regular expression literal will be performed just once, the first time it is evaluated. Otherwise, the substitutions will be performed every time the literal generates a Regexp object.

/m

/.../m

MultilineMode.
Normally, "." matches any character except a newline. With the /m option, "." matches anycharacter.

/x

/.../x

ExtendedMode.
Complex regular expressions can be difficult to read. The 'x' option allows you to insert spaces, newlines, and comments in the pattern to make it more readable.

Match operators

Once you have a regular expression object, you can match it against a string using Regexp.match(string) or the match operators =~ (positive match) and !~ (negative match). The match operators are defined for both String and Regexp objects. At least one operand of the match operator must be a regular expression.
– The match operators return the character position at which the match occurred.

$& – receives the part of the string that was matched by the pattern (matched part)
$+ – contents of the highest-numbered group matched in the last successful pattern match. This variable is local to the current scope.
$` – receives the part of the string that preceded the match$' – receives the string after the match$= – If set to any value apart from nil or false, all pattern matches will be case insensitive, string comparisons will ignore case, and string hash values will be case insensitive.
– The match also sets the thread-globalvariables $~ and $1 through $9. The variable $~ is a MatchData object that holds everything you may want to know about the match. $1, and so on, hold the values of parts of the match.

Patterns

– Within a pattern, all characters except: .|()[]{}+\^$*? match themselves. If you want to match one of these special characters literally, precede it with a backslash.
– Regular expression may contain #{...} expression substitutions.

– The patterns ^ and $ match the beginning and end of a line, respectively.
– The sequence \A matches the beginning of a string
– \z and \Z match the end of a string. (Actually, \Z matches the end of a string unless the string ends with a \n, in which case it matches just before the \n.)
– Similarly, the patterns \b and \B match wordboundaries and nonword boundaries, respectively.Word characters are letters, numbers, and underscores.

– You can use parentheses to group terms within a regular expression. Everything within the group is treated as a single regular expression.
– Parentheses also collect the results of pattern matching. Ruby counts opening parentheses, and for each stores the result of the partial match between it and the corresponding closing parenthesis. You can use this partial match both within the rest of the pattern and in your Ruby program. Within the pattern, the sequence \1 refers to the match of the first group, \2 the second group, and so on.
– Outside the pattern, the special variables$1, $2, and so on, serve the same purpose.

Composition

You can combine regexpes together with the string interpolation mechanism. The included regexp will be surrounded by an uncapturing group.

using \1-\9show_regexp('He said "Hello"', /(\w)\1/) #-> He said "He<<ll>>o"
show_regexp('Mississippi', /(\w+)\1/) #-> M<<ississ>>ippi
show_regexp('He said "Hello"', /(["']).*?\1/) #-> He said <<"Hello">>
show_regexp("He said 'Hello'", /(["']).*?\1/) #-> He said <<'Hello'>>

In common with Perl and Python, Ruby regular expressions offer some extensions over traditional Unix regular expressions.
– All the extensions are entered between the characters (? and ).
– The parentheses that bracket these extensions are groups, but they do not generate backreferences: they do not set the values of \1 and $1 etc.

?#

(?# comment)

Inserts a comment into the pattern. The content is ignored during pattern matching.

?:

(?:re)

Makes re into a groupwithout generating backreferences.
This is often useful when you need to group a set of constructs but don't want the group to set the value of $1 or whatever.

In the example that follows, both patterns match a date with either colons or spaces between the month, day, and year. The first form stores the separator character in $2 and $4, while the second pattern doesn't store the separator in an externaldate = "12/25/01"
date =~ %r{(\d+)(/|:)(\d+)(/|:)(\d+)}
[$1,$2,$3,$4,$5] #-> ["12", "/", "25", "/", "01"]
date =~ %r{(\d+)(?:/|:)(\d+)(?:/|:)(\d+)}
[$1,$2,$3] #-> ["12", "25", "01"]

?=

(?=re)

Matches re at this point, but does not consume it (also known charmingly as "zero-widthpositivelookahead").
This lets you look forward for the context of a match without affecting$&.

In this example, the scan method matches words followed by a comma, but the commas are not included in the result.str = "red, white, and blue"
str.scan(/[a-z]+(?=,)/) #-> ["red", "white"]

?!

(?!re)

Matches if re does not match at this point.
Does not consume the match (zero-widthnegativelookahead).

For example, this matches any word that contains the letters "hot" that aren't followed by "dog", returning the end of the word in $1"hot hotdog hotlight" =~ /hot(?!dog)(\w+)/ #-> 11
$1 #-> light

?>

(?>re)

Nests an independent regular expression within the first regular expression.
This expression is anchored at the current match position. If it consumes characters, these will no longer be available to the higher-level regular expression. This construct therefore inhibits backtracking, which can be a performance enhancement.

For example, the pattern /a.*b.*a/ takes exponential time when matched against a string containing an "a" followed by a number of "b"s, but with no trailing "a." However, this can be avoided by using a nested regular expression /a(?>.*b).*a/. In this form, the nested expression consumes all the the input string up to the last possible "b" character. When the check for a trailing "a" then fails, there is no need to backtrack, and the pattern match fails promptly.require "benchmark"
include Benchmark
str = "a" + ("b" * 5000)
bm(8) do |test|
test.report("Normal:") { str =~ /a.*b.*a/ }
test.report("Nested:") { str =~ /a(?>.*b).*a/ }
end
produces:
user system total real
Normal: 0.410000 0.000000 0.410000 (0.414915)
Nested: 0.000000 0.000000 0.000000 (0.001190)

?i, ?m, ?x

(?imx)

Turns on the corresponding "i", "m" or "x" option. If used inside a group, the effect is limited to that group.

The methods String.sub and String.gsub look for a portion of a string matching their first argument and replace it with their second argument. String.sub performs one replacement, and String.gsub replaces every occurrence of the match. Both routines return a new copy of the String containing the substitutions. Mutator versions String.sub! and String.gsub!modify the original string.
– The second argument to both functions can be either a String or a block. If a block is used, it is passed the matching substring, and the block’s value is substituted into the original string.

\

Backslash sequences

– Earlier we noted that the sequences \1, \2, and so on, are available in the pattern, standing for the nth group matched so far. The same sequences are available in the second argument of sub and gsub.
– Additional backslash sequences work in substitution strings:
\& (last match)
\+ (last matched group)
\` (string prior to match)
\' (string after match)
\\ (a literal backslash).

– The method Regexp.match matches a regular expression against a string. If unsuccessful, the method returns nil. On success, it returns an instance of class MatchData. And that MatchData object gives you access to all available information about the match. All that good stuff that you can get from the $-variables is bundled in a handy little object.
– Because the match data is stored in its own object, you can keep the results of two or more pattern matches available at the same time, something you can’t do using the $-variables.
– So how do the $-variables fit in? Well, after every pattern match, Ruby stores a reference to the result (nil or a MatchData object) in a thread-local variable (accessible using $~). All the other regular expression variables are then derived from this object. Although we can’t really think of a use for the following code, it demonstrates that all the other MatchData-related $-variables are indeed slaved off the value in $~.

– A character class is a set of characters between brackets: [characters] matches any single character between the brackets. [aeiou] will match a vowel, [,.:;!?] matches punctuation, and so on. The significance of the special regular expression characters .|()[{+^$*? — is turned off inside the brackets. However, normal string substitution still occurs, so (for example) \b represents a backspace character and \n a newline.
– Within the brackets, the sequence c1-c2 represents all the characters between c1 and c2, inclusive.
– If you want to include the literal characters ] and - within a character class, they must appear at the start. Put a ^ immediately after the opening bracket to negate a character class: [^a-z] matches any character that isn't a lowercase alphabetic.
– Finally, a period . appearing outside brackets represents any character except a newline (though in multiline mode it matches a newline, too).
– The sequences \d, \D, \s, \S, \w, and \W are abbreviations for groups of characters

If you do not know the pattern that you are trying to match ahead of time (e.g. it is some form of user input), you can construct a regex from a string:
str = "this string has ruby in it"
re = "ruby"
str =~ /#{Regexp.escape(re)}/ # => 16
You can also combine components to create a new pattern:
a = 'ruby'
b = 'on rails'
str = "this string has ruby on rails in it"
str.match(/#{a} #{b}/) # => true
If you are looking for a way to create patterns from combinations of common elements, and the elements are not derived from input, it is just as easy to combine Regexp objects:
a = /ruby/
b = /on rails/
str = "this string has ruby on rails in it"
str.match(/#{a} #{b}/) # => true

If r stands for the immediately preceding regular expression within a pattern, then
r* — matches zero or more occurrences of r.
r+ — matches one or more occurrences of r.
r? — matches zero or one occurrence of r.
r{m,n} — matches at least “m” and at most “n” occurrences of r.
r{m,} — matches at least “m” occurrences of r.
r{m} — matches exactly “m” occurrences of r.
These patterns are called greedy, because by default they will match as much of the string as they can. You can alter this behavior, and have them match the minimum, by adding a question mark suffix (?).

regexp, regular expressions

How to use Ruby variables in regular expressions

If you do not know the pattern that you are trying to match ahead of time (e.g. it is some form of user input), you can construct a regex from a string:

Repetitiona = "The moon is made of cheese"
show_regexp(a, /\w+/) #-> <<The>> moon is made of cheese
show_regexp(a, /\s.*\s/) #-> The<< moon is made of >>cheese
show_regexp(a, /\s.*?\s/) #-> The<< moon >>is made of cheese
show_regexp(a, /[aeiou]{2,99}/) #-> The m<<oo>>n is made of cheese
show_regexp(a, /mo?o/) #-> The <<moo>>n is made of cheese

Works like this: the first time the associated block is called, sum is set to inject’s parameter and element is set to the first element in the collection. The second and subsequent times the block is called, sum is set to the value returned by the block on the previous call. The final value of inject is the value returned by the block the last time it was called. There’s one final wrinkle: if inject is called with no parameter, it uses the first element of the collection as the initial value and starts the iteration with the second value.

Returns an array containing the items in enumObj sorted, either according to their own <=> method, or by using the results of the supplied block. The block should return -1, 0, or +1 depending on the comparison between a and b.

This sort is inefficient: it generates two new File objects during every comparison. A slightly better technique is to use the Kernel.test method to generate the modification times directly.files = Dir["*"]
sorted = files.sort { |a,b|
test(?M, a) <=> test(?M, b)
}
sorted #-> ["mon", "tues", "wed", "thurs"]

This still generates many unnecessary Time objects. A more efficient technique is to cache the sort keys (modification times in this case) before the sort. Perl users often call this approach a Schwartzian Transform, after Randal Schwartz. We construct asorted = Dir["*"].collect { |f|
[test(?M, f), f]
}.sort.collect { |f| f[1] }
sorted #-> ["mon", "tues", "wed", "thurs"]

Returns an array of every element in enumObj for which Pattern === element.
If the optional block is supplied, each matching element is passed to it, and the block's result is stored in the output array.

– If you enclose a string in backquotes (sometimes called backticks), or use the delimited form prefixed by %x, it will (by default) be executed as a command by your underlying operating system. The value of the expression is the standard output of that command. Newlines will not be stripped, so it is likely that the value you get back will have a trailing return or linefeed character.
– The exit status of the command is available in the global variable $?.

RedefiningBackquotes

The string is passed to the method called Kernel.` (a single backquote). If you want, you can override this.

Performs a low-level select call, which waits for data to become available from input/output devices. The first three parameters are arrays of IO objects or nil. The last is a timeout in seconds, which should be an Integer or a Float. The call waits for data to become available for any of the IO objects in readArray, for buffers to have cleared sufficiently to enable writing to any of the devices in writeArray, or for an error to occur on the devices in errorArray. If one or more of these conditions are met, the call returns a three-element array containing arrays of the IO objects that were ready. Otherwise, if there is no change in status for timeout seconds, the call returns nil. If all parameters are nil, the current thread sleeps forever.

Converts "arg" to a Fixnum or Bignum. Numeric types are converted directly (with floating point numbers being truncated).
If "arg" is a String, leading radix indicators (0, 0b, and 0x) are honored. This behavior is different from that of String.to_i

Converts block to a Proc object (and therefore binds it at the point of call) and registers it for execution when the programexits.
If multiple handlers are registered, they are executed in reverse order of registration.

Converts max to an integer using max = max.to_i.abs. If the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0. Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max.
– Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program.

srand( [ Number ] ) → oldSeed

– Seeds the pseudorandom number generator to the value of Number.to_i.abs.
– If Number is omitted or zero, seeds the generator using a combination of the time, the process id, and a sequence number. (This is also the behavior if Kernel::rand is called without previously calling srand, but without the sequence.) By setting the seed to a known value, scripts can be made deterministic during testing.
– The previous seed value is returned.

Generates a Continuation object, which it passes to the associated block. Performing a cont.call will cause the callcc to return (as will falling through the end of the block). The value returned by the callcc is the value of the block, or the value passed to cont.call. Also see Kernel::throw for an alternative mechanism for unwinding a call stack.

caller( [Integer] ) → Array

Returns the current executionstack – an array containing strings in the form "file:line" or "file:line: in 'method'".
The optional Integer parameter determines the number of initial stack entries to omit from the result.

Executes its block.
If a throw is executed, Ruby searches up its stack for a catch block with a tag corresponding to the throw's symbol. If found, that block is terminated, and catch returns the value given to throw. If throw is not called, the block terminates normally, and the value of catch is the value of the last expression evaluated. catch expressions may be nested, and the throw call need not be in lexicalscope.

Returns the string resulting from applying aFormatString to any additional arguments.
– Within the format string, any characters other than format sequences are copied to the result.
– A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character.
– The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation.
– The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field.
– For numeric fields, the precision controls the number of decimal places displayed.
– For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.)
Field types
b – Convert argument as a binary number.
c – Argument is the numeric code for a single character.
d – Convert argument as a decimal number.
E – Equivalent to 'e', but uses an uppercase E to indicate the exponent.
e – Convert floating point argument into exponential notation with one digit before the decimal point. The precision determines the number of fractional digits (defaulting to six).
f – Convert floating point argument as [[visible space]-]ddd.ddd, where the precision determines the number of digits after the decimal point.
G – Equivalent to 'g', but use an uppercase 'E' in exponent form.
g – Convert a floating point number using exponential form if the exponent is less than -4 or greater than or equal to the precision, or in d.dddd form otherwise.
i – Identical to 'd'.
o – Convert argument as an octal number.
s – Argument is a string to be substituted. If the format sequence contains a precision, at most that many characters will be copied.
u – Treat argument as an unsigned decimal number.
X – Convert argument as a hexadecimal number using uppercase letters.
x – Convert argument as a hexadecimal number.
Flag characters
[space] (bdeEfgGioxXu) – Leave a space at the start of positive numbers.
# (beEfgGoxX) – Use an alternative format. For the conversions 'o', 'x', 'X', and 'b', prefix the result with "0", "0x", "0X", and "0b", respectively. For 'e', 'E', 'f', 'g', and 'G', force a decimal point to be added, even if no digits follow. For 'g' and 'G', do not remove trailing zeros.
+ (bdeEfgGioxXu) – Add a leading plus sign to positive numbers.
- (all) – Left-justify the result of this conversion.
0 (zero) (all) – Pad with zeros, not spaces.
* (all) – Use the next argument as the field width. If negative, left-justify the result. If the asterisk is followed by a number and a dollar sign, use the indicated argument as the width.

scanf for Ruby scans an input string or stream according to a aFormatString, as described below ("Conversions"), and returns an array of matches between the format and the input. The format is defined in a string, and is similar (though not identical) to the formats used in Kernel#printf and Kernel#sprintf.
The format may contain conversion specifiers, which tell scanf what form (type) each particular matched substring should be converted to (e.g., decimal integer, floating point number, literal string, etc.) The matches and conversions take place from left to right, and the conversions themselves are returned as an array.
The format string may also contain characters other than those in the conversion specifiers. White space (blanks, tabs, or newlines) in the format string matches any amount of white space, including none, in the input. Everything else matches only itself.
Scanning stops, and scanf returns, when any input character fails to match the specifications in the format string, or when input is exhausted, or when everything in the format string has been matched. All matches found up to the stopping point are returned in the return array (or yielded to the block, if a block was given).
==Block usage
When called with a block, scanf keeps scanning the input, cycling back to the beginning of the format string, and yields a new array of conversions to the block every time the format string is matched (including partial matches, but not including complete failures). The actual return value of scanf when called with a block is an array containing the results of all the executions of the block.
==Conversions
The single argument to scanf is a format string, which generally includes one or more conversion specifiers. Conversion specifiers begin with the percent character ('%') and include information about what scanf should next scan for (string, decimal number, single character, etc.).
There may be an optional maximum field width, expressed as a decimal integer, between the % and the conversion. If no width is given, a default of `infinity' is used (with the exception of the %c specifier; see below). Otherwise, given a field width of n for a given conversion, at most n characters are scanned in processing that conversion. Before conversion begins, most conversions skip white space in the input string; this white space is not counted against the field width.
The following conversions are available. (See the files EXAMPLES and tests/scanftests.rb for examples.)
[%]
Matches a literal `%'. That is, `%%' in the format string matches a single input `%' character. No conversion is done, and the resulting '%' is not included in the return array.
[d]
Matches an optionally signed decimal integer.
[u]
Same as d.
[i]
Matches an optionally signed integer. The integer is read in base 16 if it begins with `0x' or `0X', in base 8 if it begins with `0', and in base 10 other- wise. Only characters that correspond to the base are recognized.
[o]
Matches an optionally signed octal integer.
[x,X]
Matches an optionally signed hexadecimal integer,
[f,g,e,E]
Matches an optionally signed floating-point number.
[s]
Matches a sequence of non-white-space character. The input string stops at white space or at the maximum field width, whichever occurs first.
[c]
Matches a single character, or a sequence of n characters if a field width of n is specified. The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.
[[]
Matches a nonempty sequence of characters from the specified set of accepted characters. The usual skip of leading white space is suppressed. This bracketed sub-expression is interpreted exactly like a character class in a Ruby regular expression. (In fact, it is placed as-is in a regular expression.) The matching against the input string ends with the appearance of a character not in (or, with a circumflex, in) the set, or when the field width runs out, whichever comes first.
===Assignment suppression
To require that a particular match occur, but without including the result in the return array, place the assignment suppression flag, which is the star character ('*'), immediately after the leading '%' of a format specifier (just before the field width, if any).
==Examples
See the files EXAMPLES and tests/scanftests.rb.
==scanf for Ruby compared with scanf in C
scanf for Ruby is based on the C function scanf(3), but with modifications, dictated mainly by the underlying differences between the languages.
===Unimplemented flags and specifiers
* The only flag implemented in scanf for Ruby is '*' (ignore upcoming conversion). Many of the flags available in C versions of scanf(4) have to do with the type of upcoming pointer arguments, and are literally meaningless in Ruby.
* The n specifier (store number of characters consumed so far in next pointer) is not implemented.
* The p specifier (match a pointer value) is not implemented.
===Altered specifiers
[o,u,x,X]
In scanf for Ruby, all of these specifiers scan for an optionally signed integer, rather than for an unsigned integer like their C counterparts.
===Return values
scanf for Ruby returns an array of successful conversions, whereas scanf(3) returns the number of conversions successfully completed. (See below for more details on scanf for Ruby's return values.)
==Return values
Without a block, scanf returns an array containing all the conversions it has found. If none are found, scanf will return an empty array. An unsuccesful match is never ignored, but rather always signals the end of the scanning operation. If the first unsuccessful match takes place after one or more successful matches have already taken place, the returned array will contain the results of those successful matches.
With a block scanf returns a 'map'-like array of transformations from the block -- that is, an array reflecting what the block did with each yielded result from the iterative scanf operation. (See "Block usage", above.)
==Test suite
scanf for Ruby includes a suite of unit tests (requiring the TestUnit package), which can be run with the command ruby tests/scanftests.rb or the command make test.
==Current limitations and bugs
When using IO#scanf under Windows, make sure you open your files in binary mode:
File.open("filename", "rb")
so that scanf can keep track of characters correctly.
Support for character classes is reasonably complete (since it essentially piggy-backs on Ruby's regular expression handling of character classes), but users are advised that character class testing has not been exhaustive, and that they should exercise some caution in using any of the more complex and/or arcane character class idioms.
==Technical notes
===Rationale behind scanf for Ruby
The impetus for a scanf implementation in Ruby comes chiefly from the fact that existing pattern matching operations, such as Regexp#match and String#scan, return all results as strings, which have to be converted to integers or floats explicitly in cases where what's ultimately wanted are integer or float values.
===Design of scanf for Ruby
scanf for Ruby is essentially a -to- converter.
When scanf is called, a FormatString object is generated from the format string ("%d%s...") argument. The FormatString object breaks the format string down into atoms ("%d", "%5f", "blah", etc.), and from each atom it creates a FormatSpecifier object, which it saves.
Each FormatSpecifier has a regular expression fragment and a "handler" associated with it. For example, the regular expression fragment associated with the format "%d" is "([-+]?\d+)", and the handler associated with it is a wrapper around String#to_i. scanf itself calls FormatString#match, passing in the input string. FormatString#match iterates through its FormatSpecifiers; for each one, it matches the corresponding regular expression fragment against the string. If there's a match, it sends the matched string to the handler associated with the FormatSpecifier.
Thus, to follow up the "%d" example: if "123" occurs in the input string when a FormatSpecifier consisting of "%d" is reached, the "123" will be matched against "([-+]?\d+)", and the matched string will be rendered into an integer by a call to to_i.
The rendered match is then saved to an accumulator array, and the input string is reduced to the post-match substring. Thus the string is "eaten" from the left as the FormatSpecifiers are applied in sequence. (This is done to a duplicate string; the original string is not altered.)
As soon as a regular expression fragment fails to match the string, or when the FormatString object runs out of FormatSpecifiers, scanning stops and results accumulated so far are returned in an array.
==License and copyright
Copyright:: (c) 2002-2003 David Alan Black
License:: Distributed on the same licensing terms as Ruby itself

MySQL modules — dev.mysql.com/downloads/ruby.html
There are two modules for connecting to a MySQL database server from Ruby:
MySQL/Ruby is built on top of the MySQL C API, and provides the same functions for Ruby programs that the MySQL C API provides for C programs (tmtm.org/en/mysql/ruby).
Ruby/MySQL is written in pure Ruby, and implements (mostly) the same interface as MySQL/Ruby. (This module is also included in the Ruby on Rails distribution) (tmtm.org/en/ruby/mysql).
MySQL/Ruby and Ruby/MySQL are both written and maintained by Tomita "tommy" Masahiro.
Ruby DBI is a database-independent API for Ruby that uses the above modules to work with MySQL. (ruby-dbi.rubyforge.org)
You can install MySQL/Ruby using the Ruby Gems
packaging manager:
$ sudo gem install mysql
More to read:
dev.mysql.com/usingmysql/ruby — Using MySQL With Ruby

The two-parameter form sends "String" on an existing connection.
The four-parameter form sends "String" to port on hostName.

Net::SMTP

Session.sendmail( src, from, to )

Sends header and body lines to the sendmail server.
The from parameter is used as the sender's name in the MAIL FROM: command, and to is either a string or an array of strings containing the recipients for the RCPT TO: command.
Lines to be sent are fetched by invoking src.each.
The terminating '.' and QUIT are sent automatically.

Class for command-line option analysis. It is much more advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented solution.
Features
- The argument specification and the code to handle it are written in the same place.
- It can output an option summary; you don’t need to maintain this string separately.
- Optional and mandatory arguments are specified very gracefully.
- Arguments can be automatically converted to a specified class.
- Arguments can be restricted to a certain set.