Ruby manual with samples. VERY simple to use. Consists of only one page. Can be extended or modified by any one at any time.

Ruby.on-page.netbeta
What is it? It’s a Ruby manual

– VERY simple to use

– Consists of only one page

– Includes many samples

– Can be extended or modified by
any one at any time.
Switch to edit mode [F2]

How to use it? Just type the word or symbol you are looking for

Where to type? Right here and right now in your browser
(or you can press Ctrl+V for searching the clipboard text)

– You will be instantly moved to the description or sample of your keyword

– If there are many includes, you can navigate via the Up/Down arrows

– For example try to type some of it: sample, community, case, file, #, ...

– For more tips you can read the little FAQ below

– Don't miss anything – subscribe to this RSS 2.0 feed and watch for project evolution

Show block
FAQ and some useful tips
Hide block

? Structure of data on the page – 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.
Hide block
Test sandbox sample table [sample]
sample
Sample text block
Some description of Ruby not sample...
For samples there is the right side of the page →
All changes of sandbox will not appear on the original page and will not be visible for you after refresh.
sample syntax
def Syntax sample
puts 'with multi line'
end
Description of sample syntax
 

sample
It is sample using of sample :)
Do not duplicate keywords! Many same keywords means many garbage in the future. There are many "sample" keywords just for sample...
 
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)
links, sites
Resources
ruby-lang.org – Ruby language home page 
rubycentral.org
rubyforge.org – A SourceForge-like home for all kinds of Ruby projects
ruby-doc.org/docs/ProgrammingRuby – An on-line copy of the first edition of the book Programming Ruby, by Dave Thomas. (ebook)
ruby-doc.org - docs and online reference
tryruby.hobix.com – Try Ruby in your web browser
rubycentral.com
rubylearning.org - Free Online Ruby Course
rubylearning.comLearning Ruby Tutorial
rubylearning.com/jobs/ruby_jobs.html - Ruby India Jobs
rubycorner.com – Directory for blogs related to Ruby
rubyrockstars.com – Ruby Jobs
snippets.dzone.com/tag/ruby – public source code repository
rubyonrails.com – open source web application framework "Ruby on Rails" written in the Ruby language (often shortened to "Rails", or "RoR")
pleac.sourceforge.net/pleac_ruby – In this document, you'll find an implementation of the Solutions of the Perl Cookbook in the Ruby language.
links
Community
groups.google.com/group/comp.lang.ruby – Google group: 5.4k members, 35k topics
groups.google.com/group/ruby-talk-google – Google group: 771 members, 7.8k topics
sitepoint.com/forums/forumdisplay.php?f=227 –  SitePoint Ruby 
tech.groups.yahoo.com/group/puneruby - PuneRuby RUG

ruby-forum.comForum List
devpals.com/forumdisplay.php?f=6 – Even Ruby developers need help sometimes. Whether it be Rails or anything else, this is the place to find answers
irc.freenode.net/#ruby-lang – the #ruby-lang irc channel averages 150+ users
lingr.com/room/5Rfd8nM5tMF – Ruby Chat Room
links
Blogs
rubyinside.com – dedicated to Ruby and its associated technologies, including Ruby on Rails
rubygarden.org
rubylearning.com/blog - Learning Ruby blog
redhanded.hobix.com - Why's Ruby Blog
Advantages
Reflection. As well as supporting reflection into both classes and individual objects, Ruby lets you traverse the list of currently active objects.
 – Marshalling. Ruby objects can be serialized and deserialized, allowing them to be saved externally and transmitted across networks. A full distributed object system, DRb, is written in about 200 lines of Ruby code.
 – Libraries. Ruby has a large (and growing) collection of libraries. All major Internet protocols are supported, as are most major databases. Extending Ruby is simple compared with (say) Perl.
 – Threads. Ruby has built-in support for threads, and doesn’t rely on the underlying operating system for thread support.
 – Object specialization. You can add methods to individual objects, not just classes. This can be useful when defining specialized behavior for objects (for example, determining how they respond to GUI events).
 – Exceptions. Ruby has a fully object-oriented, extensible exception model.
 

 
 

helloworld
"Hello World" program
puts "Hello, World" #--> Hello, World
 
Syntax
# comment
Single line comment
 

comment
# Ruby treats nil as a false value in conditions, # you could write the following to process the lines in a file.
 
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 more rvalues than lvalues, the extra rvalues are ignored. If an assignment has just one lvalue 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 discarded
class Test def val=(val) @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
 

returning
a = b = c = 0 #--> 0 a = b = 1 + 2 + 3 a #-->6 b #-->6 a = (b = 1 + 2) + 3 a #-->6 b #-->3 File.open(name = gets.chomp) [ 3, 1, 7, 0 ].sort.reverse #-->[7, 3, 1, 0]
if returns
song_type = if song.mp3_type == MP3::Jazz if song.written < Date.new(1935, 1, 1) Song::TradJazz else Song::Jazz end else Song::Other end
if returns in next lines
wer = if (false) 1 else 2 end puts wer #-> 2
case returns
rating = case votes_cast when 0...10 then Rating::SkipThisOne when 10...50 then Rating::CouldDoBetter else Rating::Rave end
multiple, multy
multi return
def multy return 1, 2, 3 end w1, w2, w3 = multy puts w1 #--> 1 puts w2 #--> 2 puts w3 #--> 3
conditions returns
part = [0, 1] puts val = part && part[1] || '1' #-> 1 puts val = part && part[2] || '2' #-> 2
 
Parallel assignment
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 expand arrays using parallel assignment
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 assignment
a, b = b, a #swap the values in two variables x = 0 #-> 0 a, b, c = x, (x += 1), (x += 1) #-> [0, 1, 2] a, b, c = 1, "cat", [ 3, 4, 5 ] a = [1, 2, 3, 4] b, c = a #-> b == 1, c == 2 b, *c = a #-> b == 1, c == [2, 3, 4] b, c = 99, a #-> b == 99, c == [1, 2, 3, 4] b, *c = 99, a #-> b == 99, c == [[1, 2, 3, 4]] b, c = 99, *a #-> b == 99, c == 1 b, *c = 99, *a #-> b == 99, c == [1, 2, 3, 4]
 
Nested assignments
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.
 

nested assignments
b, (c, d), e = 1,2,3,4 #-> b == 1, c == 2, d == nil, e == 3 b, (c, d), e = [1,2,3,4] #-> b == 1, c == 2, d == nil, e == 3 b, (c, d), e = 1,[2,3],4 #-> b == 1, c == 2, d == 3, e == 4 b, (c, d), e = 1,[2,3,4],5 #-> b == 1, c == 2, d == 3, e == 5 b, (c,*d), e = 1,[2,3,4],5 #-> b == 1, c == 2, d == [3, 4], e == 5
 
Comparison
== 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
 

 
document here, here document
Here document 
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 document
aString = <<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
indent the terminator
print <<-STRING1, <<-STRING2 Concat STRING1 enate STRING2 produces: Concat enate
quoting rules
a = 123 print <<HERE Double quoted \ here document. Sum = #{a + 1} HERE print <<-'THERE' This is single quoted. The above used #{a + 1} THERE produces: Double quoted here document. Sum = 124 This is single quoted. The above used #{a + 1}
 
null
nil
Object, just like any other, that happens to represent nothing.
spaceship
<=>
Compares two values, returning -1, 0, or +1 depending on whether the first is less than, equal to, or greater than the second.
 

 
$_ variable
Global variable $_
 

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 finished executing (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.
 

BEGIN & END blocks
BEGIN {puts "begin code 1"} END {puts "end code 1"} puts "line 2" BEGIN {puts "begin code 2"} END {puts "end code 2"} puts "line 3" produces: begin code 1 begin code 2 line 1 line 2 line 3 end code 2 end code 1
 
General Delimited Input
There are alternative forms of literal strings, arrays, regular expressions, and shell commands 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.

%qSingle-quoted string
%Q, %Double-quoted string
%wArray of tokens
%W – Array of tokens with substitutions
%rRegular expression pattern
%x – Shell command
 

using
var = 'Exp' %q/this is a string #{var}/ #-> this is a string #{var} %Q-string #{var}- #-> string Exp %(a (nested) string var=#{var}) #-> a (nested) string var=Exp (%w<q va\ r e r t y>)[1] #-> va r ['q', var, 'e', 'r', 't', 'y'][1] #-> Exp puts %q{def fred(a) a.each { |i| puts i } end} produces: def fred(a) a.each { |i| puts i } end
%w %W samples
value = 1 a = %w{ #{value} } # => ["\#{value}"] b = %W{ #{value} } # => ["1"]
 
:
Symbols
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 not nil or the constant false is true.
 – However, C, C++, and Perl programmers sometimes fall into a trap. The number zero is not interpreted as a false value. Neither is a zero-length string. This can be a tough habit to break.
 

zero, zero-length string
nil and false are false, others – true
puts ( nil ? 'true' : 'false' ) #-> false puts ( false ? 'true' : 'false' ) #-> false puts ( '' ? 'true' : 'false' ) #-> true puts ( 0 ? 'true' : 'false' ) #-> true puts ( 'w' ? 'true' : 'false' ) #-> true
 
The Value of Logical Expressions
 – 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).
 

and
nil and true #-->nil false and true #-->false 99 and false #-->false 99 and nil #-->nil 99 and "cat" #-->"cat"
 
&&, and
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.
 

or
false or nil #-->nil nil or false #-->false 99 or false #-->99
A common Ruby idiom makes use of this.
puts ( ((myhash ||= {})['key'] ||= []) << 'arrEl_1' << 'arrEl_2' )[1] #->arrEl_2
 
defined?
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.
 

defined?
defined? 1 #-->"expression" defined? dummy #-->nil defined? printf #-->"method" defined? String #-->"constant" defined? $_ #-->"globalvariable" defined? Math::PI #-->"constant" defined? a = 1 #-->"assignment" defined? 42.abs #-->"method"
 
Variables
About
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).
 

 
 

variable reference
person1 = "Tim" person2 = person1 person1[0] = 'J' person1 #-->"Jim" person2 #-->"Jim"
 
localVar, _localVar
parameter
method
Local variables, method parameters, and method names should all start with a lowercase letter or with an underscore.
 

Local variables
vname _27 varName var_name variable7
Local variable
person = "Tim" person.id #-->936870 person.class #-->String person #-->"Tim"
 
@instanceVar
Instance variable
 

Instance variables
@_ @V @v_name
 
$globalVar
Global variable
 

Global variable samples
$Global $debug $CUSTOMER $_ $plan9
 
@@classVar
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.
 

sample
PI String MyClass RModule
 
Arrays
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.
Indexing elements
 – 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.
 – 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
Modifying elements in array
 – The [ ] operator has a corresponding [ ]= operator, which lets you set elements 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.
arr.length -> Integer
arr.size -> Integer
Returns length of array
.to_a
Converts a range to a list
 

arrays
a = [ 1, 'cat', 3.14 ] # create array with three elements a[0] # --> 1 access the first element a[2] = nil # set the third element a #--> [1, "cat", nil] arr = [ fred, 10, 3.14, "This is a string", barney("pebbles"), ] %w( first sec\ ond ) #-> ["first", "sec ond"] b = Array.new # array constructor b.class #--> Array b.length #-->0 b[0] = "second" b[1] = "array" b #-->["second", "array"] c = [] # array short constructor c.class #--> Array
string to array
a = %w{ ant bee cat dog elk } a[0] #--> "ant" a[3] #--> "dog"
array indexation (-1 = the last)
a = [ 1, 3, 5, 7, 9 ] a[1] #-->3 a[2] #-->5 a[-1] #-->9 a[99] #-->nil
subarray – arr[start, count]
a = [ 1, 3, 5, 7, 9 ] a[1, 3] #-->[3, 5, 7] a[3, 1] #-->[7] a[3, 2] #-->[7, 9]
subarraytwo-period three-period
a = [ 1, 3, 5, 7, 9 ] a[1..3] #-->[3, 5, 7] a[1...3] #-->[3, 5] a[3..3] #-->[7] a[3..1] #-->[]
set elements in array
a = [ 1, 3, 5, 7, 9 ] a[1] = "bat" #-->[1, "bat", 5, 7, 9] a[2] = "cat" #-->[1, "bat", "cat", 7, 9] a[3] = [ 9, 8 ] #-->[1, "bat", "cat", [9, 8], 9] a[6] = 99 #-->[1, "bat", "cat", [9, 8], 9, nil, 99]
set ranges elements in array, replacing elements
a = [ 1, 3, 5, 7, 9 ] #-->[1, 3, 5, 7, 9] a[2, 2] = ’cat’ #-->[1, 3, "cat", 9] a[2, 0] = ’dog’ #-->[1, 3, "dog", "cat", 9] inserting elements a[1, 1] = [ 9, 8, 7 ] #-->[1, 9, 8, 7, "dog", "cat", 9] a[0..3] = [] #-->["dog", "cat", 9] removing elements a[5..6] = 99, 98 #-->["dog", "cat", 9, nil, nil, 99, 98]
ranges to array
(1...10).to_a #-->[1, 2, 3, 4, 5, 6, 7, 8, 9] ('bar'..'bat').to_a #-->["bar", "bas", "bat"]
 
arr.sort -> Array
arr.sort {|a,b| block } -> Array
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! -> arr
arr.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.
 

Array sort
a = [ "d", "a", "e", "c", "b" ] a.sort #-> ["a", "b", "c", "d", "e"] a.sort {|x,y| y <=> x } #-> ["e", "d", "c", "b", "a"]
Array sort!
a = [ "d", "a", "e", "c", "b" ] a.sort! #-> ["a", "b", "c", "d", "e"] a #-> ["a", "b", "c", "d", "e"]
 
arr.reverse -> Array
Returns a new array using arr's elements in reverse order.
arr.reverse! -> arr or nil
Same as reverse, but returns nil if arr is unchanged (arr.length is zero or one).
 

reverse
["a", "b", "c"].reverse #->["c", "b", "a"] [1].reverse #->[1]
reverse!
a = ["a", "b", "c"] a.reverse! #->["c", "b", "a"] a #->["c", "b", "a"] [ 1 ].reverse! #->nil
 
reverse_each
Same as Array.each, but traverses arr in reverse order.
 

reverse_each
a = ["a", "b", "c"] a.reverse_each {|x| print x, " " } produces: c b a
 
arr.clear -> arr
Removes all elements from arr.
 

clear
a = ["a", "b", "c", "d", "e"] a.clear #-> []
 
arr.collect {| obj | block } -> Array
Returns a new array by invoking block once for every element, passing each element as a parameter to block.
The result of block is used as the given element in the new array.
arr.collect! {| obj | block } -> arr
Invokes block once for each element of arr, replacing the element with the value returned by block.
 

collect
a = [ "a", "b", "c", "d" ] a.collect {|x| x + "!" } #-> ["a!", "b!", "c!", "d!"] a #-> ["a", "b", "c", "d"]
collect!
a = [ "a", "b", "c", "d" ] a.collect! {|x| x + "!" } #-> ["a!", "b!", "c!", "d!"] a #-> ["a!", "b!", "c!", "d!"]
 
Hashes [hsh]
about
 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
 

hash
inst_section = { 'cello' => 'string', 'clarinet' => 'woodwind', 'drum' => 'percussion', } h = {} # ={} h.length #-->0 =length h['dog'] #-->nil
hash
h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' } h.length #-->3 length h['dog'] #-->"canine" h['cow'] = 'bovine' h[12] = 'dodecine' h['cat'] = 99 h #-->{"cow"=>"bovine", "cat"=>99, 12=>"dodecine", # "donkey"=>"asinine", "dog"=>"canine"}
 
Hash[ [ key => value ]* ] -> Hash
Creates a new hash populated with the given objects.
 – Equivalent to the literal { key, value, ... }.
 – Keys and values occur in pairs, so there must be an even number of arguments.
 

Hash[
Hash["a", 100, "b", 200] #->{"a"=>100, "b"=>200} Hash["a" => 100, "b" => 200] #->{"a"=>100, "b"=>200} { "a" => 100, "b" => 200 } #->{"a"=>100, "b"=>200}
 
Hash.new( Object=nil ) -> Hash
Returns a new, empty hash.
 – If Object is specified, it will be used as the default value.
 

Hash.new
h = Hash.new("Go Fish") h["a"] = 100 h["b"] = 200 h["a"] #->100 h["c"] #->"Go Fish"
0 by defaul instead NIL
histogram = Hash.new(0) histogram['key1'] --> 0 histogram['key1'] = histogram['key1'] + 1 histogram['key1'] --> 1
 
hsh[ aKeyObject ] -> aValueObject
Element Reference
 – Retrieves the aValueObject stored for aKeyObject.
 – If not found, returns the default value.
 

Element Reference
h = { "a" => 100, "b" => 200 } h["a"] #->100 h["c"] #->nil
 
hsh[ aKeyObject ] = aValueObject -> aValueObject
hsh.store( aKeyObject, aValueObject ) -> aValueObject (Synonym)
Element AssignmentAssociates 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).
 

Element Assignment
h = { "a" => 100, "b" => 200 } h["a"] = 9 h["c"] = 4 h #->{"a"=>9, "b"=>200, "c"=>4}
 
hsh == anOtherHash -> true or false
Equality
 – Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash.
 

Equality
h1 = { "a" => 1, "c" => 2 } h2 = { "a" => 1, "c" => 2, 7 => 35 } h3 = { "a" => 1, "c" => 2, 7 => 35 } h4 = { "a" => 1, "d" => 2, "f" => 35 } h1 == h2 #->false h2 == h3 #->true h3 == h4 #->false
 
hsh.default -> Object
Returns the "default value" that is, the value returned for a key that does not exist in the hash.
 – Defaults to nil.
hsh.default = Object -> hsh
Sets the "default value"
 

default
h = { "a" => 100, "b" => 200 } h.default = "Go fish" h.default #->Go fish h["a"] #->100 h["z"] #->"Go fish"
 
hsh.delete( aKeyObject ) -> aValueObject
hsh.delete( aKeyObject ) {| aKeyObject | block } -> aValueObject
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.
 

delete
h = { "a" => 100, "b" => 200 } h.delete("a") #->100 h.delete("z") #->nil h.delete("z") { |el| "#{el} not found" } #->"z not found"
 
hsh.delete_if {| key, value | block } -> hsh
Deletes every key-value pair from hsh for which block evaluates to true.
 

delete_if
h = { "a" => 100, "b" => 200, "c" => 300 } h.delete_if {|key, value| key >= "b" } #->{"a"=>100}
 
hsh.sort -> Array
hsh.sort {|a, b| block } -> Array
Converts hsh to a nested array of [key, value] arrays and sorts it, using  Array.sort.
 

Hash sort
h = { "a" => 20, "b" => 30, "c" => 10 } h.sort #-> [["a", 20], ["b", 30], ["c", 10]] h.sort {|a,b| a[1]<=>b[1]} #-> [["c", 10], ["a", 20], ["b", 30]]
 
hsh.clear -> hsh
Removes all key-value pairs from hsh.
 

clear
h = {"a" => 100, "b" => 200} h.clear #-> {}
 
hsh.each {| key, value | block } -> hsh
hsh.each_pair {| key, value | block } -> hsh (Synonym)
Calls block once for each key in hsh, passing the key and value as parameters.
 

each
h = { "a" => 100, "b" => 200 } h.each {|key, value| print key, " is ", value, "\n" } produces: a is 100 b is 200
 
hsh.each_key {| key | block } -> hsh
Calls block once for each key in hsh, passing the key as a parameter.
 

each_key
h = { "a" => 100, "b" => 200 } h.each_key {|key| puts key } produces: a b
 
hsh.each_value {| value | block } -> hsh
Calls block once for each key in hsh, passing the value as a parameter.
 

each_value
h = { "a" => 100, "b" => 200 } h.each_value {|value| puts value } produces: 100 200
 
hsh.empty? -> true or false
Returns true if hsh contains no key-value pairs.
 

empty?
{}.empty? #->true
 
hsh.fetch( aKeyObject [, aDefObject ] ) -> Object
hsh.fetch( aKeyObject ) {| aKeyObject | block } -> Object
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.
 

fetch
h = { "a" => 100, "b" => 200 } h.fetch("a") #->100 h.fetch("z", "go fish") #->"go fish" h.fetch("z") { |el| "go fish, #{el}"} #->"go fish, z"
The following example shows that an exception is raised if the key is not found and a default value is not supplied.
h = { "a" => 100, "b" => 200 } h.fetch("z") produces: prog.rb:2:in `fetch': key not found (IndexError) from prog.rb:2
 
hsh.has_key?( aKeyObject ) -> true or false
Synonyms:
hsh.include?( aKeyObject ) -> true or false
hsh.key?( aKeyObject ) -> true or false
hsh.member?( aKeyObject ) -> true or false
Returns true if the given key is present in hsh.
 

has_key?
h = { "a" => 100, "b" => 200 } h.has_key?("a") #->true h.has_key?("z") #->false
 
hsh.has_value?( aValueObject ) -> true or false
hsh.value?( aValueObject ) -> true or false (Synonym)
Returns true if the given value is present for some key in hsh.
 

has_value?
h = { "a" => 100, "b" => 200 } h.has_value?(100) #->true h.has_value?(999) #->false
 
hsh.index( aValueObject ) -> aKeyObject
Returns the key for a given value.
 – If not found, returns the default value.
 

index
h = { "a" => 100, "b" => 200 } h.index(200) #->"b" h.index(999) #->nil
 
hsh.indexes( [ key ]+ ) -> Array
hsh.indices( [ key ]+ ) -> Array (Synonym)
Returns a new array consisting of values for the given key(s).
 – Will insert the default value for keys that are not found.
 

indexes
h = { "a" => 100, "b" => 200, "c" => 300 } h.indexes("a", "c") #->[100, 300] h.indexes("a", "c", "z") #->[100, 300, nil]
 
hsh.invert -> Hash
Returns a new hash created by using hsh's values as keys, and the keys as values.
 

invert
h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 } h.invert #->{0=>"a", 100=>"n", 200=>"d", 300=>"y"}
 
hsh.keys -> Array
Returns a new array populated with the keys from this hash.
 

keys
h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 } h.keys #->["a", "b", "c", "d"]
 
hsh.values -> Array
Returns a new array populated with the values from hsh.
 

values
h = { "a" => 100, "b" => 200, "c" => 300 } h.values #->[100, 200, 300]
 
hsh.length -> Fixnum
hsh.size -> Fixnum (Synonym)
Returns the number of key-value pairs in the hash.
 

length
h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 } h.length #->4 h.delete("a") #->200 h.length #->3
 
hsh.rehash -> hsh
Rebuilds the hash based on the current hash values for each key.
 – If values of key objects have changed since they were inserted, this method will reindex hsh.
 – If Hash.rehash is called while an iterator is traversing the hash, an IndexError will be raised in the iterator.
 

rehash
a = [ "a", "b" ] c = [ "c", "d" ] h = { a => 100, c => 300 } h[a] #->100 a[0] = "z" h[a] #->nil h.rehash #->{["z", "b"]=>100, ["c", "d"]=>300} h[a] #->100
 
hsh.reject {| key, value | block } -> Hash
Same as Hash.delete_if, but works on (and returns) a copy of the hsh.
 – Equivalent to hsh.dup.delete_if
hsh.reject! {| key, value | block } -> hsh or nil
Equivalent to Hash.delete_if, but returns nil if no changes were made.
 

 
hsh.replace( anOtherHash ) -> hsh
Replaces the contents of hsh with the contents of anOtherHash.
 

replace
h = { "a" => 100, "b" => 200 } h.replace({ "c" => 300, "d" => 400 }) #->{"c"=>300, "d"=>400}
 
hsh.shift -> Array or nil
Removes a key-value pair from hsh and returns it as the two-item array [ key, value ], or nil if the hash is empty.
 

shift
h = { 1 => "a", 2 => "b", 3 => "c" } h.shift #->[1, "a"] h #->{2=>"b", 3=>"c"}
 
hsh.to_a -> Array
Converts hsh to a nested array of [ key, value ] arrays.
 

to_a
h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 } h.to_a #->[["a", 100], ["c", 300], ["d", 400]]
 
hsh.to_s -> String
Converts hsh to a string by converting the hash to an array of [ key, value ] pairs and then converting that array to a string using Array.join with the default separator.
 

to_s
h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 } h.to_s #->"a100c300d400"
 
hsh.update( anOtherHash ) -> hsh
Adds the contents of anOtherHash to hsh, overwriting entries with duplicate keys with those from anOtherHash.
 

update
h1 = { "a" => 100, "b" => 200 } h2 = { "b" => 254, "c" => 300 } h1.update(h2) #->{"a"=>100, "b"=>254, "c"=>300}
inline
h1 = {:a => 100, :b => 200} h1.update(:b => 254, :c => 300) #-> {:b=>254, :c=>300, :a=>100}
 
Ranges
fflop
Ranges as Conditions
  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
digits = 0..9 digits.include?(5) #-->true digits.min #-->0 digits.max #-->9 digits.reject {|i| i < 5 } #-->[5, 6, 7, 8, 9] digits.each {|digit| dial(digit) } #-->0..9
fflop, flip-flop
Ranges as Conditions
while line = gets puts line if line =~ /start/ .. line =~ /end/ end (1..10) === 5 #-->true (1..10) === 15 #-->false (1..10) === 3.14159 #-->true ('a'..'j') === 'c' #-->true ('a'..'j') === 'z' #-->false
fflop, flip-flop
Ranges as Conditions
File.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, ...)
 

iterator for Fibonacci numbers
def fibUpTo(max) n1, n2 = 1, 1 while n1 <= max yield n1 # invoke block with passing value n1, n2 = n2, n1+n2 # and calculate next end end fibUpTo(1000) { |term| print term, " " } produces: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
 
do
...
end
For multiline block
do |param1, param2, ...|
...
end
Multiline block with parameters
method { ... }
method(params) { ... }
Block associated with method can be invoked inside method by yield
block_given?
Returns true if a block is associated with the current method
proc {...}
lambda {...}
Converts a block to a Proc object
Shortcut for Proc.new { ... }
.call
Calls Proc object
 

iterator for I/O
f = File.open("testfile") f.each do |line| puts line end f.close #produces: This is line one This is line two This is line three And so on...
lambda sample
def n_times(thing) return lambda {|n| thing * n } end p1 = n_times(23) p1.call(3) #-->69 p1.call(4) #-->92 p2 = n_times("Hello ") p2.call(3) #-->"Hello Hello Hello "
return from blocks, returning in blocks
return in block
def sample1 (1..5).each do |v| return v end "done" end def sample2 p = Proc.new do return 2 end p.call "done" end def sample3 p = lambda do return 3 end p.call "done" end sample1 # => 1 sample2 # => 2 sample3 # => "done"
Checking number of arguments
nonchecked = Proc.new { |a, b, c| [ a, b, c ] } checked = lambda { |a, b, c| [ a, b, c ] } nonchecked.call(1, 2) # => [1, 2, nil] nonchecked.call(1, 2, 3, 4) # => [1, 2, 3] checked.call(1, 2) #--> will raise an exeption "wrong number of arguments (2 for 3) (ArgumentError)"
local variables in block
a = [1, 2] b = 'cat' a.each {|b| c = b * a[1] } a #-->[1, 2] b #-->2 changed defined?(c) #-->nil not defined
Proc object
def 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
yield
def 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
parametrs to yield
def call_block yield("hello", 99) end call_block {|str, num| ... }
yield
class 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
Passing block throw parameter
songlist = SongList.new class JukeboxButton < Button def initialize(label, &action) super(label) @action = action end def button_pressed @action.call(self) end end start_button = JukeboxButton.new("Start") { songlist.start } pause_button = JukeboxButton.new("Pause") { songlist.pause }
 
Control Structures
if | unless ... [then]
...
elsif ... [then]
...
else
...
end
Unless is a negated form of the if statement.
If you lay out your if statements on multiple lines, you can leave off the then keyword.
If is an expression, not a statement — it returns a value.
if | unless ... : command
elsif ... : command
else command
end
You can get even terser and use a colon ":" in place of the then.
puts "..." if | unless var > 3
Shortcut for if
... ? ... : ...
Ruby also supports the C-style conditional expression.
 

Sample
if count > 10 puts "Try again" elsif tries == 3 puts "You lose" else puts "Enter a number" end
if, unless
mon, day, year = $1, $2, $3 if date =~ /(\d\d)-(\d\d)-(\d\d)/ puts "a = #{a}" if debug print total unless total.zero? File.foreach("/etc/fstab") do |line| next if line =~ /^#/ #--># Skip comments parse(line) unless line =~ /^$/ #--># Don't parse empty lines end
unless
if true then puts 'first' else puts 'second' end unless false
 
switch
case var
when "debug"
...
when /p\s+(\w+)/
...
when "quit", "exit"
exit
else
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.
leap = case
when year % 400 == 0: true
when year % 100 == 0: false
else year % 4 == 0
end
As with if statements, you can use a colon ":" in place of the then.
 

case sample
case input_line when "debug" dump_debug_info dump_symbols when /p\s+(\w+)/ dump_variable($1) when "quit", "exit" exit else print "Illegal command: #{input_line}" end
using case
rating = case votes_cast when 0...10 then Rating::SkipThisOne when 10...50 then Rating::CouldDoBetter else Rating::Rave end
":" in place of the then
leap = case when year % 400 == 0: true when year % 100 == 0: false else year % 4 == 0 end
case with region
kind = 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 pattern
case 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 objects
case shape when Square, Rectangle # ... when Circle # ... when Triangle # ... else # ... end
 
Loops
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 local variables 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 local variable 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.
 

Scope in block
[ 1, 2, 3 ].each do |x| y = x + 1 end [ x, y ] produces: prog.rb:4: undefined local variable or method `x' for main:Object (NameError)
local variable already exists
x = nil y = nil [ 1, 2, 3 ].each do |x| y = x + 1 end [ x, y ] #-->[3, 4]
the Ruby interpreter just needs to have seen it
if 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.
... until [becomes true]
Shortcut
 

while sample
while weight < 100 and num_pallets <= 30 pallet = next_pallet() weight += pallet.weight num_pallets += 1 end
while
file = File.open("ordinal") while line = file.gets puts(line) if line =~ /third/ .. line =~ /fifth/ end #or slightly differently while file.gets print if ~/third/ .. ~/fifth/ end produces: third fourth fifth
while with block
print "Hello\n" while false begin print "Goodbye\n" end while false produces: Goodbye
until
until play_list.duration > 60 play_list.add(song_list.pop) end
 
n.times
Iterates n times, executing the block inside
3.upto(6)
6.downto(3)
Iterating up and down between two integers
.step(from, step)
Iteration with step
 

samples
5.times { print "*" } #-->***** 3.upto(6) {|i| print i } #-->3456 99.downto(95) {|i| print i, " " } #-->99 98 97 96 95 50.step(80, 5) {|i| print i, " " } #-->50 55 60 65 70 75 80
 
loop do
...
end
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.
next
Skips to the end of the loop, effectively starting the next iteration.
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 sample
i=0 loop do i += 1 next if i < 3 print i break if i > 4 end produces: 345
while sample
while line = gets next if line =~ /^\s*#/ # skip comments break if line =~ /^END/ # stop at end # substitute stuff in backticks and try again redo if line.gsub!(/`(.*?)`/) { eval($1) } # process line ... end
retry
for i in 1..100 print "Now at #{i}. Restart? " retry if gets =~ /^y/i end
retry will reevaluate any arguments to the iterator before restarting it
def do_until(cond) break if cond yield retry end i = 0 do_until(i > 10) do print i, " " i += 1 end produces: 0 1 2 3 4 5 6 7 8 9 10
break with argument
result = while line = gets break(line) if line =~ /answer/ end process_answer(result) if result
 
for i in 1..3
print 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
 

for in sample
for i in ['fee', 'fi', 'fo', 'fum'] print i, " " end produces: fee fi fo fum
for in with region
for i in 1..3 print i, " " end produces: 1 2 3
with array
for 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
 
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
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 multiple arguments 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.
def method(arg1, &block)
If the last parameter in a method definition is prefixed with an ampersand, any associated block 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
Class Method. 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.
def initialize(param, ...)
...
end
Calls for new object initialization 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 private methods.
Class.superclass
Returns the superclass
hierarchy
Class.ancestors
Returns the array of inheritance hierarchy:
this class, mixins list, suerclass, ... , Object, Kernel
super
super(param, ...)
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.
calling method, parameters, return
obj.method
obj.method()
obj.method "param1", param2, param3
obj.method("param1", param2, param3)
 – 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.
hash, parameters
obj.method(param,
{
'key1' => val1,
'key2' => val2
})
obj.method(param, 'key1' => val1, 'key2' => val2)
obj.method(param, :key1 => :val1, :key2 => :val2)
 – You can place key => value pairs in an argument list, as long as they follow any normal