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

What is it?It’s a Ruby manual

– VERY simple to use (if you know the trick)

– Consists of only one page

– Includes many samples

– Can be extended by anyone

Switch to view 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 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
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. (

 – 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 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. (
download, installer
RubyInstaller (compiled with MinGW) —
Other ways —
API, core, docs, latest, lib, stdlib
latest Core
latest Standard Library
(additonal libraries included with the standard Ruby distribution, such as CGI, OpenURI, and REXML)

2.0.0 core --
         std-lib --
1.9.3 core —
         std-lib —
1.8.7 core —
         std-lib —
1.8.6 core —
         std-lib —
books, links, sites
Resources – Ruby language home page, (offsite, oficial site) — extremely original way to learn Ruby. – A SourceForge-like home for all kinds of Ruby projects – An on-line copy of the first edition of the book Programming Ruby, by Dave Thomas. (ebook) (Pragmatic Programmer's Guide) - docs and online reference - Free Online Ruby Course
rubylearning.comLearning Ruby Tutorial - Ruby India Jobs – Directory for blogs related to Ruby – public source code repository – open source web application framework "Ruby on Rails" written in the Ruby language (often shortened to "Rails", or "RoR") – In this document, you'll find an implementation of the Solutions of the Perl Cookbook in the Ruby language.
Community – Google group: 5.4k members, 35k topics – Google group: 771 members, 7.8k topics –  SitePoint Ruby - PuneRuby RUG

ruby-forum.comForum List – the #ruby-lang irc channel averages 150+ users
Blogs – dedicated to Ruby and its associated technologies, including Ruby on Rails - Learning Ruby blog

hello, world
Hello World
Obligatory "Hello World!"

"Hello World" program
puts "Hello, World" #--> Hello, World
# comment
Single line comment
a = 10
b = 20
tambah = a + b
puts tambah
a = 10
b = 20
tambah = a + b
puts tambah
a = "hello"
b = "world"
c = "!"
d = a + b + c
puts d
a = "hello"
b = "world"
c = "!"
d = a + b + c 
puts d

# Ruby treats nil as a false value in conditions, # you could write the following to process the lines in a file.
 – 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) #creates only writable member of class @val = val return 99 end end t = a = t.val = 2 a #-->2
Anything that can reasonably return a value does.
The if and case statements both return the value of the last expression executed

a = b = c = 0 #--> 0 a = b = 1 + 2 + 3 a #-->6 b #-->6 a = (b = 1 + 2) + 3 a #-->6 b #-->3 = 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 <, 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 # Really a return of an array.
def multy return 1, 2, 3 end w1, w2, w3 = multy # assigns each element of the array returned to the variables (See parallel assignment, below) 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
== 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
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.
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).
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
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}
Object, just like any other, that happens to represent nothing.
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 ="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
%xShell command

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

:Object :myVariable
Boolean Expressions
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).

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.

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
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? 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"
Bitwise Operators[bit by bit operations, bits level operations, working with bits]
numeric & numeric → numeric
Binary AND
1 & 1 = 1
0 & 1 = 0
1 & 0 = 0
0 & 0 = 0
numeric | numeric → numeric
Binary OR
1 & 1 = 1
0 & 1 = 1
1 & 0 = 1
0 & 0 = 0
numeric ^ numeric → numeric
Binary XOR
1 & 1 = 0
0 & 1 = 1
1 & 0 = 1
0 & 0 = 0
flip bits, flipping, reverse
~numeric → numeric
Binary NOT
1 & 1 = 0
0 & 1 = 1
1 & 0 = 1
0 & 0 = 0
Unary operator
left shift
numeric << numeric → numeric
Binary Shift Left
right shift
numeric >> numeric → numeric
Binary Shift Right

a = 0b00000011 b = 0b00000101 puts 'a = %08b, %d' % [a, a] #-> a = 00000011, 3 puts 'b = %08b, %d' % [b, b] #-> b = 00000101, 5 puts 'AND = %08b, %d' % [a&b, a&b] #-> AND = 00000001, 1 puts 'OR = %08b, %d' % [a|b, a|b] #-> OR = 00000111, 7 puts 'XOR = %08b, %d' % [a^b, a^b] #-> XOR = 00000110, 6 c = 0b10000011 puts 'c = %08b, %d' % [c, c] #-> c = 10000011, 131 puts 'NOT = %08b, %d' % [~c, ~c] ] #-> NOT = 101111100, -132 puts '<< 2 = %08b, %d' % [c << 2, c << 2] #-> << 2 = 1000001100, 524 puts '>> 1 = %08b, %d' % [c >> 1, c >> 1] #-> >> 1 = 01000001, 65
Symbols[:, symbol]
:", .to_sym, string 2 symbol, string to symbol, to symbol, to_sym
:name → symbol
:"string" → symbol
"string".to_sym → symbol
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 contexts
module One class Fred end $f1 = :Fred end module Two Fred = 1 $f2 = :Fred end def Fred() end $f3 = :Fred $ #-> 2514190 $ #-> 2514190 $ #-> 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

"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

Symbol.all_symbols → array
Returns an array of all the symbols currently in Ruby’s symbol table.

Symbol.all_symbols.size #-> 903 Symbol.all_symbols[1,20] produces: [:floor, :ARGV, :Binding, :symlink, :chown, :EOFError, :$;, :String, :LOCK_SH, :"setuid?", :$<, :default_proc, :compact, :extend, :Tms, :getwd, :$=, :ThreadGroup, :wait2, :$>]
.id2name, symbol to string
symbol.id2name → string
symbol.to_s → string (synonym)
Returns the name or string corresponding to symbol.

:fred.id2name #-> "fred"
symbol.inspect → string
Returns the representation of sym as a symbol literal.

:fred.inspect #-> ":fred"
symbol to integer, symbol to number
symbol.to_i → fixnum
Returns an integer that is unique for each symbol within a particular execution of a program.

:fred.to_i #-> 9809 "fred".to_sym.to_i #-> 9809
Returns a Proc object which respond to the given method by symbol.
&:*, blockinator, pretzel colon
In general &:method_name is a shorthand for &:method_name.to_proc (analog for using &my_proc), but it can not be used everywhere (see samples).

Read the discussion "What does map(&:name) mean"

class Symbol def to_proc do |obj, *args| obj.send self, *args end end end
&:method_name usage
p (1..3).collect #-> [1, 2, 3] p (1..3).collect {|obj| obj.to_s} #-> ["1", "2", "3"] p (1..3).collect {|obj|} #-> ["1", "2", "3"] p (1..3).collect(&(:to_s.to_proc)) #-> ["1", "2", "3"] p (1..3).collect(&:to_s.to_proc) #-> ["1", "2", "3"] p (1..3).collect(&:to_s) #-> ["1", "2", "3"] # but! p 1.to_s #-> "1" p #-> "1" p 1.send(:to_s) #-> "1" p & #-> undefined method `call' for :to_s:Symbol (NoMethodError) # so it can not be used everywhere
Another sample
my_transform = do |obj| obj + '*' end p ['a', 'b', 'c'].collect(&my_transform) #-> ["a*", "b*", "c*"] p :upcase.to_proc #-> Proc:0x029f7db0 p'a') #-> "A" p ['a', 'b', 'c'].collect(&:upcase.to_proc) #-> ["A", "B", "C"] p ['a', 'b', 'c'].collect(&:upcase) #-> ["A", "B", "C"]
sample from # instead of { |p| p.activated? }.collect{ |p| p.title}
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"
my, var
localVar, _localVar
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" #-> 936870 person.class #-> String person #-> "Tim"
Instance variable

Instance variables
@_ @V @v_name
Global variable

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

PI String MyClass RModule
Array class[Array, Array class, arrays, list, rray]
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
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. 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.
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.

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 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"
ranges to array
(1...10).to_a #-> [1, 2, 3, 4, 5, 6, 7, 8, 9] ('bar'..'bat').to_a #-> ["bar", "bas", "bat"]
Array.[](*args) → array
Creates new array populated with the given objects, obj=nil) → array
Creates new array with size copies of obj (that is, size references to the same obj) → array
Creates copy of the array passed as a parameter (the array is generated by calling #to_ary on the parameter). {|index| block } → array
New array of the given size is created. Each element in this array is calculated by passing the element’s index to the given block and storing the return value.

Array.[]( 1, 'a', /^A/ ) #-> [1, "a", /^A/] Array[ 1, 'a', /^A/ ] #-> [1, "a", /^A/] [ 1, 'a', /^A/ ] #-> [1, "a", /^A/] #-> [] #-> [nil, nil], "A") #-> ["A", "A", "A", "A", "A"] # only one copy of the object is created a =, #-> a = [{}, {}] a[0]['cat'] = 'feline' #-> a = [{"cat"=>"feline"}, {"cat"=>"feline"}] a[1]['cat'] = 'Felix' #-> a = [{"cat"=>"Felix"}, {"cat"=>"Felix"}] # here multiple copies are created a = { } #-> a = [{}, {}] a[0]['cat'] = 'feline' #-> a = [{"cat"=>"feline"}, {}] squares = {|i| i*i} #-> [0, 1, 4, 9, 16] copy = #-> [0, 1, 4, 9, 16]
array &, intersection, set intersection
array_1 & array_2 → array
Intersection — returns a new array containing elements common to the two arrays, with no duplicates.

[1, 1, 3, 5] & [1, 2, 3] #-> [1, 3]
* array, array *, repetition
array * int → array
Returns a new array built by concatenating the int copies of self.

[1, 2, 3] * 3 #-> [1, 2, 3, 1, 2, 3, 1, 2, 3]
* array, array *
array * str → string
Equivalent to array.join(str)

[1, 2, 3] * "," #-> "1,2,3" ['12', '34', '5', '231'].join(", ") #-> "12, 34, 5, 231"
+ array, array +
array_1 + array_2 → array
Concatenation — returns a new array built by concatenating the two arrays together to produce a third array.

[1, 2, 3] + [4, 5] #-> [1, 2, 3, 4, 5]
- 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.)

[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.

[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.

["a", "a", "c"] <=> ["a", "b", "c"] #-> -1 [1, 2, 3, 4, 5, 6] <=> [1, 2] #-> +1
== array, array ==
array_1 == array_2 → bool
Equality — Two arrays are equal if they contain the same number of elements and if each element is equal to (according to Object.==) the corresponding element in the other array.

["a", "c"] == ["a", "c", 7] #-> false ["a", "c", 7] == ["a", "c", 7] #-> true ["a", "c", 7] == ["a", "d", "f"] #-> false
Element Reference

Array for samples
a = ["a", "b", "c", "d", "e"]
.at, .slice
array[index] → obj or nil → obj or nil (synonym)
array.slice(index) → obj or nil (synonym)
Returns the element at index.
Negative indices count backward from the end of the array (-1 is the last element).
Returns nil if the index (or starting index) are out of range.

a[2] + a[0] + a[1] #-> "cab" a[5] #-> nil a[6] #-> nil #=> "a" #=> "e"
-1 array, -1 index, array -1
array indexation (-1 = the last)
a = [1, 3, 5, 7, 9] a[1] #-> 3 a[2] #-> 5 a[-1] #-> 9 a[99] #-> nil
array[start, length] → array or nil
array.slice(start, length) → array or nil (synonym)
Returns a subarray starting at start and continuing for length elements

a[1, 2] #-> ["b", "c"] a[-3, 3] #-> ["c", "d", "e"] a[5, 1] #-> []
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]
subarray by range
array[range] → array or nil
array.slice(range) → array or nil (synonym)
Returns a subarray specified by range

a[1..3] #-> ["b", "c", "d"] a[4..7] #-> ["e"] a[6..10] #-> nil a[5..10] #-> []
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] #-> []
Element Assignment
array[index] = obj → obj
array[start, length] = obj or array or nil → obj or array or nil
array[range] = obj or array or nil → obj or array or nil
Sets the element at index, or replaces a subarray starting at start and continuing for length elements, or replaces a subarray specified by range. If indices are greater than the current capacity of the array, the array grows automatically. 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.

a = a[4] = "4"; #-> [nil, nil, nil, nil, "4"] a[0, 3] = ['a', 'b', 'c'] #-> ["a", "b", "c", nil, "4"] a[1..2] = [1, 2] #-> ["a", 1, 2, nil, "4"] a[0, 2] = "?" #-> ["?", 2, nil, "4"] a[0..2] = "A" #-> ["A", "4"] a[-1] = "Z" #-> ["A", "Z"] a[1..-1] = nil #-> ["A"]
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]
array splice, insert, splice
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]
array.assoc(obj) → array or nil
Searches through an array whose elements are also arrays comparing obj with the first element of each contained array using obj.==. Returns the first contained array that matches (that is, the first associated array), or nil if no match is found. See also Array#rassoc.

s1 = ["colors", "red", "blue", "green"] s2 = ["letters", "a", "b", "c"] s3 = "foo" a = [s1, s2, s3] a.assoc("letters") #-> ["letters", "a", "b", "c"] a.assoc("red") #-> nil a.assoc("foo") #-> nil
array.choice → obj
Choose a random element from an array.

a = ["a", "b", "c", "d", "e"] a.choice #-> "e" a.choice #-> "a" a.choice #-> "b" a = [] a.choice #-> nil
array.clear → array
Removes all elements from array.

a = ["a", "b", "c"] a.clear #-> []
.collect, .map
array.collect {|item| block } → array {|item| 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.
.collect!, .map!
array.collect! {|item| block } → array! {|item| block } → array
Invokes block once for each element of array, replacing the element with the value returned by block.

a = ["a", "b", "c", "d"] a.collect {|x| x + "!" } #-> ["a!", "b!", "c!", "d!"] a #-> ["a", "b", "c", "d"]
a = ["a", "b", "c", "d"] a.collect! {|x| x + "!" } #-> ["a!", "b!", "c!", "d!"] a #-> ["a!", "b!", "c!", "d!"]
array.combination(n) { |c| block } → array
array.combination(n) → enumerator
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.

a = [1, 2, 3, 4] a.combination(1).to_a #-> [[1],[2],[3],[4]] a.combination(2).to_a #-> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] a.combination(3).to_a #-> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]] a.combination(4).to_a #-> [[1,2,3,4]] a.combination(0).to_a #-> [[]] # one combination of length 0 a.combination(5).to_a #-> [] # no combinations of length 5
array.compact → array
Returns a copy of array with all nil elements removed.

["a", nil, "b", nil, "c", nil].compact #-> ["a", "b", "c"]
array.compact! → array or nil
Removes nil elements from array. Returns nil if no changes were made.

["a", nil, "b", nil, "c"].compact! #-> ["a", "b", "c"] ["a", "b", "c"].compact! #-> nil
array.concat(other_array) → array
Appends the elements in other_array to self.

a = ["a", "b"] a.concat( ["c", "d"] ) #-> ["a", "b", "c", "d"] a #-> ["a", "b", "c", "d"]
.count, array count
array.count → int
array.count(obj) → int
array.count {|item| block } → int
Returns the number of elements. 
If an argument is given, counts the number of elements which equals to obj. 
If a block is given, counts the number of elements yielding a true value.

a = [1, 2, 4, 2] a.count #-> 4 a.count(2) #-> 2 a.count {|x| x % 2 == 0} #-> 3
.cycle, array cycle
array.cycle {|obj| block }
array.cycle(n) {|obj| block }
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.

a = ["a", "b", "c"] a.cycle {|x| puts x } # prints: a, b, c, a, b, c, ... (forever) a.cycle(2) {|x| puts x } # prints: a, b, c, a, b, c
.delete, array delete, array delete elements, array elements deletion, delete all, delete by content match, delete from array
array.delete(obj) → value of deleted element or nil
array.delete(obj) { block } → obj or nil
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.

a = ["a", "b", "b", "b", "c"] a.delete("b") #-> "b" a #-> ["a", "c"] a.delete("z") #-> nil a.delete("z") { "not found" } #-> "not found"
.delete_at, array delete element, array delete_at, delete at, delete by index, delete element from array
array.delete_at(index) → value of deleted element or nil
Deletes the element at the specified index, returning that element, or nil if the index is out of range. 
See also array.slice!

a = %w(ant bat cat dog) a.delete_at(2) #-> "cat" a #-> ["ant", "bat", "dog"] a.delete_at(99) #-> nil arr = [1, 2, 3] arr.delete_at(1) #-> 2 arr #-> [1, 3]
.delete_if, array delete_if, delete if
array.delete_if {|item| block } → array
Deletes every element of self for which block evaluates to true.

a = ["a", "b", "c"] a.delete_if {|x| x >= "b" } #-> ["a"]
.drop, array drop
array.drop(n) → array
Drops first n elements from array, and returns rest elements in an array.
Does not modify the original array.

a = [1, 2, 3, 4, 5, 0] a.drop(3) #-> [4, 5, 0] a #-> [1, 2, 3, 4, 5, 0]
.drop_while, array drop_while
array.drop_while {|item| block } → array
Drops elements up to, but not including, the first element for which the block returns nil or false and returns an array containing the remaining elements. 
Does not modify the original array.

a = [1, 2, 3, 4, 5, 0] a.drop_while {|i| i < 3 } #-> [3, 4, 5, 0] a #-> [1, 2, 3, 4, 5, 0]
.each, array each
array.each {|item| block } → array
Calls block once for each element in array, passing that element as a parameter.
Returns initial array.

a = ["a", "b", "c"] a.each {|x| print x, " -- " } produces: a -- b -- c --
.each_index, array each_index
array.each_index {|index| block } → array
Same as array.each, but passes the index of the element instead of the element itself.
Returns initial array.

a = ["a", "b", "c"] a.each_index {|x| print x, " -- " } produces: 0 -- 1 -- 2 --
.empty?, array empty?
array.empty? → true or false
Returns true if self array contains no elements.

[].empty? #-> true
.eql?, array eql?
array.eql?(other) → true or false
Returns true if array and other are the same object, or are both arrays with the same content.

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

a = [11, 22, 33, 44] a.fetch(1) #-> 22 a.fetch(-1) #-> 44 a.fetch(4, 'cat') #-> "cat" a.fetch(4) {|i| i*i } #-> 16
.fill, array fill
array.fill(obj) → array
array.fill(obj, start [, length]) → array
array.fill(obj, range ) → array
array.fill {|index| block } → array
array.fill(start [, length] ) {|index| block } → array
array.fill(range) {|index| block } → 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.

a = ["a", "b", "c", "d"] a.fill("x") #-> ["x", "x", "x", "x"] a.fill("z", 2, 2) #-> ["x", "x", "z", "z"] a.fill("y", 0..1) #-> ["y", "y", "z", "z"] a.fill {|i| i*i } #-> [0, 1, 4, 9] a.fill(-2) {|i| i*i*i } #-> [0, 1, 8, 27]
.index, array index
array.index(obj) → int or nil
array.index {|item| block } → int or nil
This is an alias of array.find_index
Returns the index of the first object in self such that is == to obj. 
If a block is given instead of an argument, returns first object for which block is true. Returns nil if no match is found.

a = ["a", "b", "c"] a.index("b") #-> 1 a.index("z") #-> nil a.index{|x| x=="b" } #-> 1
.first, array first, first n
array.first → obj or nil
array.first(n) → array
Returns the first element, or the first n elements of the array. 
If the array is empty, the first form returns nil, and the second form returns an empty array.

a = ["q", "r", "s", "t"] a.first #-> "q" a.first(1) #-> ["q"] a.first(3) #-> ["q", "r", "s"]
.flatten, array flatten
array.flatten → array
array.flatten(level) → array
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.

s = [1, 2, 3] #-> [1, 2, 3] t = [4, 5, 6, [7, 8]] #-> [4, 5, 6, [7, 8]] a = [s, t, 9, 10] #-> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10] a.flatten #-> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [1, 2, [3, [4, 5]]] a.flatten(1) #-> [1, 2, 3, [4, 5]]
convert array to hash, hash, to_h, to_hash
a1 = ['apple', 1, 'banana', 2] h1 = Hash[*a1.flatten] #->{ 'apple' => 1, 'banana' => 2} a2 = [['apple', 1], ['banana', 2]] h2 = Hash[*a2.flatten] #->{ 'apple' => 1, 'banana' => 2}
.flatten!, array flatten!
array.flatten! → array or nil
array.flatten!(level) → array or nil
Flattens self in place.     
Returns nil if no modifications were made (i.e., array contains no subarrays).
If the optional level argument determines the level of recursion to flatten.

a = [1, 2, [3, [4, 5]]] a.flatten! #-> [1, 2, 3, 4, 5] a.flatten! #-> nil a #-> [1, 2, 3, 4, 5] a = [1, 2, [3, [4, 5]]] a.flatten!(1) #-> [1, 2, 3, [4, 5]]
.frozen?, array frozen?
array.frozen? → true or false
Return true if this array is frozen (or temporarily frozen while being sorted).

.hash, array hash
array.hash → fixnum
Compute a hash-code for this array. 
Two arrays with the same content will have the same hash code (and will compare using eql?).

.include?, array include?, includes?
array.include?(obj) → true or false
Returns true if the given object is present in array (that is, if any object == anObject), false otherwise.

a = ["a", "b", "c"] a.include?("b") #-> true a.include?("z") #-> false
.indexes, .indices, array indexes
array.indexes(i1, i2, ... iN) → array
array.indices(i1, i2, ... iN) → array
Use array.values_at

.replace, array replace
array.replace(array2) → array
Replaces the contents of self with the contents of array2, truncating or expanding if necessary.

a = ["a", "b", "c", "d", "e"] a.replace(["x", "y", "z"]) #-> ["x", "y", "z"] a #-> ["x", "y", "z"]
.insert, array insert
array.insert(index, obj...) → array
Inserts the given values before the element with the given index.
Or after the element if the given index is negative (or before if go from the end of array).

a = %w{a b c d} a.insert(2, 99) #-> ["a", "b", 99, "c", "d"] a[-2] #-> "c" a.insert(-2, 1, 2, 3) #-> ["a", "b", 99, "c", 1, 2, 3, "d"]
.inspect, array inspect
array.inspect → string
Create a printable version of array.

.last, array last, last item, last n elements, last n items
array.last → obj or nil
array.last(n) → array
Returns the last element(s) of array. 
If the array is empty, the first form returns nil.

["w", "x", "y", "z"].last #-> "z"
.length, .size, array length, array size
array.length → int
array.size → int (alias)
Returns length of array (number of elements). May be zero.

[1, 2, 3, 4, 5].length #-> 5
.collect, .map, array collect, array map
array.collect {|item| block } → array {|item| block } → array
Invokes block once for each element of self. Creates a new array containing the values returned by the block. 
See also Enumerable#collect.

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

arr.push(Object) → arr
Appends the given argument(s) to the end of arr (as with a stack).
arr.pop → obj or nil 
Removes the last element from arr and returns it, or nil if the array is empty (as with a stack).

Array push
a = [ "a", "b", "c" ] a.push("d", "e", "f") #-> ["a", "b", "c", "d", "e", "f"]
Array pop
a = [ "a", "m", "z" ] a.pop #-> "z" a #-> ["a", "m"]
arr.shift → obj or nil
arr.shift(n) → newArray
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.
arr.unshift(obj, ...) → anArray
Prepends objects to the front of self, moving other elements upwards

args = [ "-m", "-q", "filename" ] args.shift #=> "-m" args #=> ["-q", "filename"] args = [ "-m", "-q", "filename" ] args.shift(2) #=> ["-m", "-q"] args #=> ["filename"]
a = [ "b", "c", "d" ] a.unshift("a") #--> ["a", "b", "c", "d"] a.unshift(1, 2) #--> [ 1, 2, "a", "b", "c", "d"]
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).

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

a = ["a", "b", "c"] a.reverse_each {|x| print x, " " } produces: c b a
Converts a range to a list

Hashes[Hash, hsh]
 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

inst_section = { 'cello' => 'string', 'clarinet' => 'woodwind', 'drum' => 'percussion', } h = {} h.length #-> 0 h['dog'] #-> nil
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["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} Object=nil ) → Hash
Returns a new, empty hash.
 – If Object is specified, it will be used as the default value.
h ="Go Fish") h["a"] = 100 h["b"] = 200 h["a"] #-> 100 h["c"] #-> "Go Fish"
0 by defaul instead NIL
histogram = 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 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
 – 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.

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"

h = { "a" => 100, "b" => 200 } h.default = "Go fish" h.default #-> Go fish h["a"] #-> 100 h["z"] #-> "Go fish"
delete key, delete_key, hash delete, hsh delete
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.

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

h = { "a" => 100, "b" => 200, "c" => 300 } h.delete_if {|key, value| key >= "b" } #->{"a"=>100}
hash sort, sort hash
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]] Hash[h.sort {|a,b| a[1]<=>b[1]}] #-> {"c" => 10, "b" => 30, "a" => 20}
hsh.clear → hsh
Removes all key-value pairs from hsh.

h = {"a" => 100, "b" => 200} h.clear #-> {}
.each, each hash, each hsh
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.

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.

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.

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? #->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.

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
has key, hash include, hsh include
hsh.has_key?( aKeyObject ) → true or false
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.

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.

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.

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.

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.

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.

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.

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

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

a = [ "a", "b" ] c = [ "c", "d" ] h = { a => 100, c => 300 } h[a] #-> 100 a[0] = "z" h[a] #-> nil h.rehash #-> {["z", "b"]=>100, ["c", "d"]=>300} h[a] #-> 100
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.

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.

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.

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.

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.

h1 = { "a" => 100, "b" => 200 } h2 = { "b" => 254, "c" => 300 } h1.update(h2) #->{"a"=>100, "b"=>254, "c"=>300}
h1 = {:a => 100, :b => 200} h1.update(:b => 254, :c => 300) #-> {:b=>254, :c=>300, :a=>100}
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.

range include, ranges include
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
 – 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
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
For multiline block
do |param1, param2, ...|
Multiline block with parameters
method { ... }
method(params) { ... }
Block associated with method can be invoked inside method by yield
Returns true if a block is associated with the current method
proc {...}
lambda {...}
Converts a block to a Proc object
Shortcut for { ... }
Calls Proc object

iterator for I/O
f ="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) #-->69 #-->92 p2 = n_times("Hello ") #-->"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 = do return 2 end "done" end def sample3 p = lambda do return 3 end "done" end sample1 #-> 1 sample2 #-> 2 sample3 #-> "done"
Checking number of arguments
nonchecked = { |a, b, c| [ a, b, c ] } checked = lambda { |a, b, c| [ a, b, c ] }, 2) #-> [1, 2, nil], 2, 3, 4) #-> [1, 2, 3], 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 #-> 'cat' not changed defined?(c) #-> nil not defined
Proc object
def times(n) return { |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) #--> 8 santa = times("Ho! ") #--> "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.
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| ... }
class File def File.my_open(*args) result = file =*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 = class JukeboxButton < Button def initialize(label, &action) super(label) @action = action end def button_pressed end end start_button ="Start") { songlist.start } pause_button ="Pause") { songlist.pause }
Control Structures
else if, elseif
if | unless ... [then]
elsif ... [then]
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
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.

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 File.foreach("/etc/fstab") do |line| next if line =~ /^#/ #-> Skip comments parse(line) unless line =~ /^$/ #-> Don't parse empty lines end
if true then puts 'first' else puts 'second' end unless false
case var
when "debug"
when /p\s+(\w+)/
when "quit", "exit"
   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
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
  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]
  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]
until [becomes true]
The until loop is the opposite; it executes the body until the condition becomes true.
... until [becomes true]

while sample
while weight < 100 and num_pallets <= 30 pallet = next_pallet() weight += pallet.weight num_pallets += 1 end
file ="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 play_list.duration > 60 play_list.add(song_list.pop) end
Iterates n times, executing the block inside
Iterating up and down between two integers
.step(from, step)
Iteration with step

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
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.
Skips to the end of the loop, effectively starting the next iteration.
  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.
Repeats the loop from the start, but without reevaluating the condition or fetching the next element (in an iterator).
  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
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
cycle, each_with_index, for in, for-in, forin, loop
['a', 'b', 'c'].each_with_index do |item, index|
    puts "#{item} -- #{index}"

#a -- 0
#b -- 1
#c -- 2
#=> ["a", "b", "c"]
cycle, for in, for-in, forin, loop
for i in 1..3
print i, " "
  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|
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
two vars
aHash = {:v => 1, :b => 2} for par, val in aHash puts "#{par} = #{val}" end produces: v = 1 b = 2
for in with region
for i in 1..3 print i, " " end produces: 1 2 3
with array
for i in"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 = for genre in periods print genre, " " end produces: Classical Jazz Rock
Classes, Modules, Mixins, and Multiple Inheritance
class ClassName
Class definition. First letter of ClassName must be in uppercase
class SubClass < ParentClass
Class inheritance
function, procedure, sub
def instance_method(param, ...)
Instance Method
def method(arg1="Val1", arg2="Val2", ...)
Default values for a method’s arguments
def instance_method(param1, *args)
 – 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.
block argument, pass block
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, ...)
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, ...)
Calls for new object initialization when you use
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 is “dangerous,” or modify the receiver.
Method acts as querie.
If you omit the receiver, it defaults to self, the current object.
This defaulting mechanism is how Ruby implements private methods.
parent class, super class
Returns the superclass
Returns the array of inheritance hierarchy:
this class, mixins list, superclass, ... , Object, Kernel
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 "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
'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 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.
class ClassName
attr_reader :artist, :name, :duration
attr_writer :duration
#-- instead --
def name
def duration
def duration=(new_duration)
@duration = new_duration
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
Method protection
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.
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.

Class sample
class Song MAX_TIME = 5*60 # constant @@plays = 0 # class variable def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end def [](index) # def [] invokes by songObj[7] with 7 as parametr @songs[index] end end
class KaraokeSong < Song def initialize(name, artist, duration, lyrics) super(name, artist, duration) @lyrics = lyrics end end
class Base end class Derived < Base end Base.superclass #-> Object Derived.superclass #-> Base
class KaraokeSong < Song def to_s super + " [#@lyrics]" end end
Arguments to array
def varargs(arg1, *rest) # *args "Got \#{arg1} and \#{rest.join(', ')}" end varargs("one") #-> "Got one and " varargs("one", "two") #-> "Got one and two" varargs "one", "two", "three" #-> "Got one and two, three"
def meth_two(arg) case when arg > 0 "positive" when arg < 0 "negative" else "zero" end end meth_two(23) #-> "positive" meth_two(0) #-> "zero"
return array
def meth_three 100.times do |num| square = num*num return num, square if square > 1000 end end meth_three #-> [32, 1024] num, square = meth_three num #-> 32 square #-> 1024
passing array
def five(a, b, c, d, e) "I was passed #{a} #{b} #{c} #{d} #{e}" end five(1, 2, 3, 4, 5 ) #-> "I was passed 1 2 3 4 5" five(1, 2, 3, *['a', 'b']) #-> "I was passed 1 2 3 a b" five(*(10..14).to_a) #-> "I was passed 10 11 12 13 14"
class, definition, method
The following all define class methods within class Demo.
class Demo def Demo.meth1 # ... end def self.meth2 # ... end class << self def meth3 # ... end end end
class method calling
File.size("testfile") #-> 66 Math.sin(Math::PI/4) #-> 0.707106781186548
self.class #-> Object self.frozen? #-> false frozen? #-> false #-> 967900 id #-> 967900 # we could not call the method # class without a receiver. This is because class is also a keyword in Ruby
Passing block
class TaxCalculator def initialize(name, &block) @name, @block = name, block end def get_tax(amount) "#@name on #{amount} = #{ }" end end tc ="Sales tax") {|amt| amt * 0.075 } tc.get_tax(100) #-> "Sales tax on 100 = 7.5" tc.get_tax(250) #-> "Sales tax on 250 = 18.75"
Class sample
class Shape def Shape.triangle(side_length), side_length*3) end def Shape.square(side_length), side_length*4) end end
class Song def title # attribute getter (reader) @title # returns instance variable end def title=(title) # attribute setter (writer) @title = title end end aSong.title = "Chicago" # aSong.title=("Chicago")
attr_reader attr_writer sample
class Song attr_reader :name, :artist, :duration attr_writer :duration end song ="Bicylops", "Fleck", 260) song.artist #-> "Fleck" #-> "Bicylops" song.duration #-> 260 song.duration = 257 song.duration #-> 257
Using Accessors within a Class
class BrokenAmplifier attr_accessor :left_channel, :right_channel def volume=(vol) left_channel = self.right_channel = vol end end ba = 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.
virtual attributes
class Song def duration_in_minutes @duration/60.0 # force floating point end def duration_in_minutes=(new_duration) @duration = (new_duration*60).to_i end end song ="Bicylops", "Fleck", 260) song.duration_in_minutes #--> 4.33333333333333 song.duration_in_minutes = 4.2 song.duration #--> 252
Adding functionality with a mixin
module Enumerable def find each { |val| return val if yield(val) } end end
class Array include Enumerable end
method protection
class 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 on public :method1, :method4 #=public protected :method2 #=protected private :method3 #=private end
module ModuleName
 – 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
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 $:.

2 modules with method 'sin'
module Trig PI = 3.141592654 def Trig.sin(x) # .. end def Trig.cos(x) # .. end end module Moral VERY_BAD = 0 BAD = 1 def Moral.sin(badness) # ... end end # in some third program require 'trig' require 'moral' y = Trig.sin(Trig::PI/4) wrongdoing = Moral.sin(Moral::VERY_BAD)
Mixin include
module Debug def who_am_i? "#{} (\##{}): #{self.to_s}" end end class Phonograph include Debug # ... end class EightTrack include Debug # ... end ph ="West End Blues") et ="Surrealistic Pillow") ph.who_am_i? #-> "Phonograph (#935520): West End Blues" et.who_am_i? #-> "EightTrack (#935500): Surrealistic Pillow"
class Song include Comparable def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end def <=>(other) self.duration <=> other.duration end end song1 ="My Way", "Sinatra", 225) song2 ="Bicylops", "Fleck", 260) song1 <=> song2 #-> 1 song1 < song2 #-> true song1 == song1 #-> true song1 > song2 #-> false
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
require returns true on success
result = require 'some_existing_rb_file' puts result #-> true result = require 'some_existing_rb_file' puts result #-> false
5.times do |i|"temp.rb","w") do |f| f.puts "module Temp" f.puts " def Temp.var" f.puts " #{i}" f.puts " end" f.puts "end" end load "temp.rb" puts Temp.var end produces: 0 1 2 3 4

class Module @@docs = def doc(str) @@docs[] = 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 = 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
class name, class of variable, get class, object class, variable class
Object.class → Class Name
Returns the class name of the object.

'str'.class #--> String

extend_object(Object) → Object
Extends the specified object by adding this module's constants and methods (which are added as singleton methods).
This is the callback method used by Object.extend.

module Picky def Picky.extend_object(o) if String === o print "Can't add Picky to a String\n" else print "Picky added to ", o.type, "\n" super end end end (s = Picky # Call Object.extend (s = "quick brown fox").extend Picky produces: Picky added to Array Can't add Picky to a String
Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string.
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".
Returns the internal hash key used by Hash.

test ='name', 'artist', 'dur') puts test.inspect produces: <Song:0x28bdccc @artist="artist", @duration="dur", @name="name">
inspect samples
1.inspect # => "1" (0.3).inspect # => "0.3" :Hello.inspect # => ":Hello" [ 1, 2, 3 ].inspect # => "[1, 2, 3]" { :first => 1 }.inspect # => "{:first=>1}"’_vimrc’, ’r’).inspect # => "#<File:_vimrc>"
puts test.to_s #-->#<Song:0x28bdc40> class Song def to_s "Song: #@name--#@rtist (#@duration)" end end song ="Bicylops", "Fleck", 260) song.to_s #--> "Song: Bicylops--Fleck (260)"
obj.dup → Object
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.

person1 = "Tim" person2 = person1.dup person1[0] = 'J' person1 #-->"Jim" person2 #-->"Tim"
obj.freeze → obj
Prevents further modifications to obj.
A TypeError will be raised if modification is attempted.
There is no way to unfreeze a frozen object.

a = [ "a", "b", "c" ] a.freeze a << "z" produces: prog.rb:3:in '<<': can't modify frozen array (TypeError) from prog.rb:3
person1 = "Tim" person2 = person1 person1.freeze # prevent modifications to the object person2[0] = "J" produces: prog.rb:4:in `[]=': can't modify frozen string (TypeError) from prog.rb:4
obj.frozen? → true or false
Returns the freeze status of obj.

a = ["a", "b", "c"] a.freeze #-> ["a", "b", "c"] a.frozen? #-> true
obj.extend([Module]+) → obj
Adds to obj the instance methods from each module given as a parameter.

module Mod def hello "Hello from Mod.\n" end end class Klass def hello "Hello from Klass.\n" end end k = k.hello #-> "Hello from Klass.\n" k.extend(Mod) #-> #<Klass:0x401b598c> k.hello #-> "Hello from Mod.\n"
module Humor def tickle "hee, hee!" end end a = "Grouchy" a.extend Humor a.tickle #-> "hee, hee!"
There is an interesting trick with extend. If you use it within a class definition, the module's methods become class methods.
module Humor def tickle "hee, hee!" end end class Grouchy include Humor extend Humor end Grouchy.tickle #-> "hee, hee!" a = a.tickle #-> "hee, hee!"
obj.send( Symbol  [, args ]* ) → Object
obj.__send__( aSymbol [, args ]+ ) → Object
Invokes the method identified by Symbol, passing it any arguments specified.
You can use __send__ if the name send clashes with an existing method in obj.

class Klass def hello(*args) "Hello " + args.join(' ') end end k = k.send :hello, "gentle", "readers" #-> "Hello gentle readers"
Returns the absolute value of num.

-7.abs #-> 7 111.abs #-> 111
num.integer? → true or false
Returns true if num is an Integer (including Fixnum and Bignum).

bigint, long, short
About integer
 – 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.

num = 81 6.times do puts "#{num.class}: #{num}" num *= num end produces: Fixnum: 81 Fixnum: 6561 Fixnum: 43046721 Bignum: 1853020188851841 Bignum: 3433683820292512484657849089281 Bignum: 11790184577738583171520872861412518665678211592275841109096961
123456 => 123456 # Fixnum 0d123456 => 123456 # Fixnum 123_456 => 123456 # Fixnum (underscore ignored) -543 => -543 # Fixnum (negative number) 0xaabb => 43707 # Fixnum (hexadecimal) 0377 => 255 # Fixnum (octal) -0b10_1010 => 42 # Fixnum binary (negated) 123_456_789_123_456_789 => 123456789123456789 # Bignum
?a => 97 # ASCII character ?\n => 10 # code for a newline (0x0a) ?\C-a => 1 # control a = ?A & 0x9f = 0x01 ?\M-a => 225 # meta sets bit 7 ?\M-\C-a => 129 # meta and control a ?\C-? => 127 # delete character
fixnum / numeric → numeric
fixnum.div(numeric) → numeric
Performs division: the class of the resulting object depends on the class of numeric and on the magnitude of the result.

exponential, pow
fixnum ** other → numeric
Raises fix to the other power, which may be negative or fractional.

** sample
2 ** 3 #-> 8 2 ** -1 #-> 0.5 2 ** 0.5 #-> 1.4142135623731
int.integer? → true
Always returns true.

++ → Integer
Equal to int + 1.

next #-> 2 (-1).next #-> 0
int.chr → String
Returns a string containing the ASCII character represented by the receiver's value.

65.chr #-> "A" ?a.chr #-> "a" 230.chr #-> "\346"
flt.ceil → Integer
Returns the smallest Integer greater than or equal to flt.
flt.floor → Integer
Returns the largest integer less than or equal to flt.

1.2.ceil #-> 2 2.0.ceil #-> 2 (-1.2).ceil #-> -1 (-2.0).ceil #-> -2
1.2.floor #-> 1 2.0.floor #-> 2 (-1.2).floor #-> -2 (-2.0).floor #-> -2
flt.round → Integer
Rounds flt to the nearest integer.

1.5.round #-> 2 (-1.5).round #-> -2
Equivalent to:
def round return floor(self+0.5) if self > 0.0 return ceil(self-0.5) if self < 0.0 return 0.0 end
flt.finite? → true or false
Returns true if flt is a valid IEEE floating point number (it is not infinite, and nan? is false).
flt.infinite? → nil, -1, +1
Returns nil, -1, or +1 depending on whether flt is finite, -infinity, or +infinity.

(0.0).infinite? #-> nil (-1.0/0.0).infinite? #-> -1 (+1.0/0.0).infinite? #-> 1
flt.nan? → true or false
Returns true if flt is an invalid IEEE floating point number.

a = -1.0 #-> -1.0 a.nan? #-> false a = Math.log(a) #-> NaN a.nan? #-> true
flt.to_i → Integer
Returns flt truncated to an Integer.
flt.to_s → String
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".


String class[String, strings, working with strings]
#, Substitutions
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.

r = 'E' $glob = 'G' @inst = 'I' @@const = 'C' puts "...#{r}...#{1+2}...#$glob...#@inst...#@@const..." produces: "...E...3...G...I...C..."
"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...
quotting, 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.

%q/general 'singlequoted-string'/ #-> general 'singlequoted-string' %Q!general "doublequoted-string"! #-> general "doublequoted-string" %Q{Seconds/day: #{24*60*60}} #-> Seconds/day: 86400
About string
Ruby strings are simply sequences of 8-bit bytes.
They normally hold printable characters, but that is not a requirement; a string can also hold binary data.
Strings are objects of class String.

escape using "\"
'escape using "\\"' #-> escape using "\" 'That\'s right' #-> That's right
line = "/jazz/j00319.mp3 | 2:58 | Louis Armstrong | Wonderful World" file, length, name, title = line.chomp.split(/\s*\|\s*/) name.squeeze!(" ") # removing extra spaces mins, secs = length.scan(/\d+/) puts "#{name} - #{title} (#{mins.to_i*60+secs.to_i})" produces: Louis Armstrong - Wonderful World (178)
Comparable: <, <=, ==, >=, >, between?
Enumerable: collect, detect, each_with_index, entries, find, find_all, grep, include?, map, max, member?, min, reject, select, sort, to_a

str % arg  → String
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.

"%05d" % 123 #-> "00123" "%-5s: %08x" % ["ID",] #-> "ID : 200e1670"
str * Integer → String
Returns a new String containing Integer copies of the receiver.

"Ho! " * 3 #-> "Ho! Ho! Ho! "
str + String → NewString
Returns a new String containing String concatenated to str.

"Hello from " + self.to_s #-> "Hello from main"
str << Fixnum → str
str << Object → str
str.concat( Fixnum ) → str
str.concat( Object ) → str
Concatenates the given object to str.
If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation.

a = "hello " a << "world" #-> "hello world" a << 33 #-> "hello world!" a #-> "hello world!"
str <=> String → -1, 0, +1
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.

"abcdef" <=> "abcde" #-> 1 "abcdef" <=> "abcdef" #-> 0 "abcdef" <=> "abcdefg" #-> -1 "abcdef" <=> "ABCDEF" #-> 1 $= = true "abcdef" <=> "ABCDEF" #-> 0
str == Object → true or false
str === Object → true or false (Synonym)
 – 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
 – 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.

"cat o' 9 tails" =~ "\\d" #-> 7 "cat o' 9 tails" =~ /\d/ #-> 7 "cat o' 9 tails" =~ 9 #-> false
[], substring
str[Fixnum] → Fixnum or nil
str[Fixnum, Fixnum] → String or nil
str[Range] → String or nil
str[Regexp] → String or nil
str[String] → String or nil
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.

a = "hello there" a[1] #-> 101 a[1,3] #-> "ell" a[1..3] #-> "ell" a[-3,2] #-> "er" a[-4..-2] #-> "her" a[-2..-4] #-> nil a[/th[aeiou]/] #-> "the" a["lo"] #-> "lo" a["bye"] #-> nil
str[Fixnum] = Fixnum
str[Fixnum] = String
str[Fixnum, Fixnum] = String
str[Range] = String
str[Regexp] = String
str[String] = String
Element Assignment
 – Replaces some or all of the content of str.
 – The portion of the string affected is determined using the same criteria as String.[]
 – If the replacement string is not the same length as the text it is replacing, the string will be adjusted accordingly.
 – The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment.

a = "hello"; a[2] = 96; a #-> "he`lo" a = "hello"; a[2, 4] = "xyz"; a #-> "hexyz" a = "hello"; a[-4, 2] = "xyz"; a #-> "hxyzlo" a = "hello"; a[2..4] = "xyz"; a #-> "hexyz" a = "hello"; a[-4..-2] = "xyz"; a #-> "hxyzo" a = "hello"; a[/[el]+/] = "xyz"; a #-> "hxyzo" a = "hello"; a["l"] = "xyz"; a #-> "hexyzlo" a = "hello"; a["ll"] = "xyz"; a #-> "hexyzo" a = "hello"; a["bad"] = "xyz"; a #-> "hello" a = "hello"; a[2, 0] = "xyz"; a #-> "hexyzllo"
String functions in Ruby
String methods 

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)

str.slice( Fixnum ) → Fixnum or nil
str.slice( Fixnum, Fixnum ) → String or nil
str.slice( Range ) → String or nil
str.slice( Regexp ) → String or nil
str.slice( String ) → String or nil
Synonyms for str[]

a = "hello there" a.slice(1) #-> 101 a.slice(1,3) #-> "ell" a.slice(1..3) #-> "ell" a.slice(-3,2) #-> "er" a.slice(-4..-2) #-> "her" a.slice(-2..-4) #-> nil a.slice(/th[aeiou]/) #-> "the" a.slice("lo") #-> "lo" a.slice("bye") #-> nil
str.slice!( Fixnum ) → Fixnum or nil
str.slice!( Fixnum, Fixnum ) → String or nil
str.slice!( Range ) → String or nil
str.slice!( Regexp ) → String or nil
str.slice!( String ) → String or nil
Deletes the specified portion from str, and returns the portion deleted.
 – The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment.

string = "this is a string" string.slice!(2) #-> 105 string.slice!(3..6) #-> " is " string.slice!(/s.*t/) #-> "sa st" string.slice!("r") #-> "r" string #-> "thing"
first uppercase, upper first
str.capitalize → String
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
str.capitalize! → str or nil
Modifies str by converting the first character to uppercase and the remainder to lowercase.
 – Returns nil if no changes are made.

"hello".capitalize #-> "Hello" "HELLO".capitalize #-> "Hello" "123ABC".capitalize #-> "123abc"
a = "hello" a.capitalize! #-> "Hello" a #-> "Hello" a.capitalize! #-> nil
str.downcase → String
Returns a copy of str with all uppercase letters replaced with their lowercase counterparts.
 – The operation is locale insensitive
 – Only characters "A" to "Z" are affected.
str.downcase! → str or nil
Downcases the contents of str, returning nil if no changes were made.

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

"hEllO".upcase #-> "HELLO" 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.

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

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

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

~str → Fixnum or nil
Equivalent to $_  =~ str

str.index( String [, Offset ] ) → Fixnum or nil 
str.index( Fixnum [, Offset ] ) → Fixnum or nil
str.index( Regexp [, Offset ] ) → Fixnum or nil
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.

"Ruby".index("Ru") #-> 0 "Ruby".index("r") #-> nil "Ruby".index(117) #-> 1 "Ruby".index("b") #-> 2 "Ruby".index(/.$/, 3) #-> 3 "Ruby".index(/.$/, 4) #-> nil
str.rindex( String [, Fixnum ] ) → Fixnum or nil
str.rindex( Fixnum [, Fixnum ] ) → Fixnum or nil
str.rindex( Regexp [, Fixnum ] ) → Fixnum or nil
Returns the index of the last occurrence of the given substring, character, or pattern in str.
 – Returns nil if not found.
 – If the second parameter is present, it specifies the position in the string to end the search characters beyond this point will not be considered.

"hello".rindex('e') #-> 1 "hello".rindex('l') #-> 3 "hello".rindex('a') #-> nil "hello".rindex(101) #-> 1 "hello".rindex(/[aeiou]/, -2) #-> 1
string to array
str.split( pattern=$;, [  limit  ] ) → Array
Divides str into substrings based on a delimiter, returning an array of these substrings.
 – If pattern is a String, then its contents are used as the delimiter when splitting str.
 – If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.
 – If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters.
 – If pattern 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.

" now's the time".split #-> ["now's", "the", "time"] " now's the time".split(' ') #-> ["now's", "the", "time"] " now's the time".split(/ /) #-> ["", "now's", "", "the", "time"] "1, 2.34,56, 7".split(/,\s*/) #-> ["1", "2.34", "56", "7"] "hello".split(//) #-> ["h", "e", "l", "l", "o"] "hello".split(//, 3) #-> ["h", "e", "llo"] "hi mom".split(/\s*/) #-> ["h", "i", "m", "o", "m"] "mellow yellow".split("ello") #-> ["m", "w y", "w"] "1,2,,3,4,,".split(',') #-> ["1", "2", "", "3", "4"] "1,2,,3,4,,".split(',', 4) #-> ["1", "2", "", "3,4,,"] "1,2,,3,4,,".split(',', -4) #-> ["1", "2", "", "3", "4", "", ""]
Returns a copy of str with leading and trailing whitespace removed.
str.strip! → str or nil 
Removes leading and trailing whitespace from str. Returns nil if str was not altered.

" hello ".strip #-> "hello" "\tgoodbye\r\n".strip #-> "goodbye" " first second third \n ".strip #-> "first second third"
str.reverse → String
str.reverse! → str
Returns a new string with the characters from str in reverse order.
"reverse!" reverses str in place.

puts "abc".reverse #-> cba
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.

"12345".to_i #-> 12345 "99 red balloons".to_i #-> 99 "0x0a".to_i #-> 0 "hello".to_i #-> 0
str.chomp( String=$/ ) → String 
Returns a new String with the given record separator removed from the end of str (if present).
str.chomp!( String=$/ ) → str or nil
Modifies str in place as described for String.chomp, returning str, or nil if no modifications were made.

"hello".chomp #-> "hello" "hello\n".chomp #-> "hello" "hello \n there".chomp #-> "hello \n there" "hello".chomp("llo") #-> "he"
str.chop → String
Returns a new String with the last character removed.
If the string ends with \r\n, both characters are removed.
Applying chop to an empty string returns an empty string.
String.chomp is often a safer alternative, 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.

"string\r\n".chop #-> "string" "string\n\r".chop #-> "string\n" "string\n".chop #-> "string" "string".chop #-> "strin" "x".chop.chop #-> ""
s = "string" #-> string s.chop! #-> strin s #-> strin t = "" t.chop! #-> nil
str.count( [ String ]+ ) → Fixnum
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.

a = "hello world" a.count("lo") #-> 5 counts [lo]: he(l)(l)(o) w(o)r(l)d a.count("lo", "o") #-> 2 counts intersection [o]: hell(o) w(o)rld a.count("we", "w", "e") #-> 0 nothing to count, intersection in null a.count("rrr", "reee", "r") #-> 1 counts intersection [r]: hello wo(r)ld a.count("hello", "^l") #-> 4 counts intersection [heo]: (h)(e)ll(o) w(o)rld a.count("ej-m") #-> 4 counts [ejklm]: h(e)(l)(l)o wor(l)d
delete string, str delete, string delete
str.delete( [ String ]+ ) → String
Returns a copy of str with all characters in the intersection of its arguments deleted.
Uses the same rules for building the set of characters as String.count
str.delete!( [ String ]+ ) → str or nil 
Performs a delete operation in place, returning str, or nil if str was not modified.

"hello".delete("l","lo") #-> "heo" "hello".delete("lo") #-> "he" "hello".delete("aeioul", "^l") #-> "hll" "hello".delete("ej-m") #-> "ho" "wer'3'33".delete("'") #-> 'wer333'
each line, each string, eachline, string each
str.each( String=$/ ) {| substr | block } → str
str.each_line( String=$/ ) {| substr | block } → str (Synonym)
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.

print "Example one\n" "hello\nworld".each {|s| p s} print "Example two\n" "hello\nworld".each('l') {|s| p s} print "Example three\n" "hello\n\n\nworld".each(") {|s| p s} produces: Example one "hello\n" "world" Example two "hel" "l" "o\nworl" "d" Example three "hello\n\n\n" "world"
each byte
str.each_byte {| Fixnum | block } → str
Passes each byte in str to the given block.

"hello".each_byte {|c| print c, ' ' } produces: 104 101 108 108 111
'', ""
str.empty? → true or false
Returns true if str has a length of zero.

"hello".empty? #-> false "".empty? #-> true
str.sub( pattern, replacement ) → String
str.sub( pattern ) {| match | block } → String
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.
str.sub!( pattern, replacement ) → str or nil
str.sub!( pattern ) {| match | block } → str or nil
Performs the substitutions of String.sub in place, returning str, or nil if no substitutions were performed.

"hello".sub(/[aeiou]/, '*') #-> "h*llo" "hello".sub(/([aeiou])/, '<\1>') #-> "h<e>llo" "hello".sub('.') {|s| s[0].to_s + ' ' } #-> "104 ello"
str.gsub( pattern, replacement ) → String
str.gsub( pattern ) {| match | block } → String
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.
str.gsub!( pattern, replacement ) → str or nil
str.gsub!( pattern ) {| match | block } → str or nil
Performs the substitutions of String.gsub in place, returning str, or nil if no substitutions were performed.

"hello".gsub(/[aeiou]/, '*') #-> "h*ll*" "hello".gsub(/([aeiou])/, '<\1>') #-> "h<e>ll<o>" "hello".gsub('.') {|s| s[0].to_s + ' '} #-> "104 101 108 108 111 "
str.hex → Integer
Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number.
 – Zero is returned on error.

"0x0a".hex #-> 10 "-1234".hex #-> -4660 "0".hex #-> 0 "wombat".hex #-> 0
str.oct → Integer
Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number.
 – Returns 0 if the conversion fails.

"123".oct #-> 83 "-377".oct #-> -255 "bad".oct #-> 0 "0377bad".oct #-> 255
str iclude, string include
str.include? String → true or false
str.include? Fixnum → true or false
Returns true if str contains the given string or character.

"hello".include? "lo" #-> true "hello".include? "ol" #-> false "hello".include? ?h #-> true
str.intern → Symbol
Returns the Symbol corresponding to str, creating the symbol if it did not previously exist.

"Koala".intern #-> :Koala
str.length → Integer
str.size → Integer (Synonym)
Returns the length of str.

str.replace( String ) → str
Replaces the contents and taintedness of str with the corresponding values in String.

s = "hello" #-> "hello" s.replace "world" #-> "world"
str.scan( pattern ) → Array
str.scan( pattern ) {| match, ...| block } → str
Both forms iterate through str, matching the pattern (which may be a Regexp or a String). For each match, a result is generated and either added to the result array or passed to the block.
 – If the pattern contains no groups, each individual result consists of the matched string, $&.
 – If the pattern contains groups, each individual result is itself an array containing one entry per group.

a = "cruel world" a.scan(/\w+/) #-> ["cruel", "world"] a.scan(/.../) #-> ["cru", "el ", "wor"] a.scan(/(...)/) #-> [["cru"], ["el "], ["wor"]] a.scan(/(..)(..)/) #-> [["cr", "ue"], ["l ", "wo"]] And the block form: a.scan(/\w+/) {|w| print "<<#{w}>> " } print "\n" a.scan(/(.)(.)/) {|a,b| print b, a } print "\n" produces: <<cruel>> <<world>> rceu lowlr
str.squeeze( [ String ]* ) → NewString
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.

"yellow moon".squeeze #-> "yelow mon" " now is the".squeeze(" ") #-> " now is the" "putters shoot balls".squeeze("m-z") #-> "puters shot balls"
str.succ → String → String (Synonym)
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.
str.succ! → str! → str (Synonym)
Equivalent to String.succ , but modifies the receiver in place.

"abcd".succ #-> "abce" "THX1138".succ #-> "THX1139" "<<koala>>".succ #-> "<<koalb>>" "1999zzz".succ #-> "2000aaa" "ZZZ9999".succ #-> "AAAA0000" "***".succ #-> "**+"
str.sum( Fixnum=16 ) → Integer
Returns a basic n-bit checksum of the characters in str, where n is the optional parameter, defaulting to 16. The result is simply the sum of the binary value of each character in str modulo 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.

"Hello".swapcase #-> "hELLO" "cYbEr_PuNk11".swapcase #-> "CyBeR_pUnK11"
to Float
str.to_f → Float
Returns the result of interpreting leading characters in str as a floating point number.
 – Extraneous characters past the end of a valid number are ignored.
 – If there is not a valid number at the start of str, 0.0 is returned.
 – The method never raises an exception.

"123.45e1".to_f #-> 1234.5 "45.67 degrees".to_f #-> 45.67 "thx1138".to_f #-> 0.0
str.to_s → str
Returns the receiver.

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

.tr, transliteration 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.!( fromString, toString ) → str or nil
Translates str in place, using the same rules as
 – Returns str, or nil if no changes were made.

"hello".tr('aeiou', '*') #-> "h*ll*" "hello".tr('^aeiou', '*') #-> "*e**o" "hello".tr('el', 'ip') #-> "hippo" "hello".tr('a-y', 'b-z') #-> "ifmmp"
str.tr_s( fromString, toString ) → String
Processes a copy of str as described under, then removes duplicate characters in regions that were affected by the translation.
str.tr_s!( fromString, toString ) → str or nil
Performs String.tr_s processing on str in place, returning str, or nil if no changes were made.

"hello".tr_s('l', 'r') #-> "hero" "hello".tr_s('el', '*') #-> "h*o" "hello".tr_s('el', 'hx') #-> "hhxo"
str.unpack( format ) → Array
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.

"abc \0\0abc \0\0".unpack('A6Z6') #-> ["abc", "abc "] "abc \0\0".unpack('a3a3') #-> ["abc", " \000\000"] "aa".unpack('b8B8') #-> ["10000110", "01100001"] "aaa".unpack('h2H2c') #-> ["16", "61", 97] "\xfe\xff\xfe\xff".unpack('sS') #-> [-2, 65534] "now=20is".unpack('M*') #-> ["now is"] "whole".unpack('xax2X2X1X2a') #-> ["h", "e", "l", "l", "o"]
\nnn, \xxx
Cyrillic unpack
"\320\240\320\270".to_a.pack('A*') --> 'Ри'
str.upto( String ) {| s | block } → str
Iterates through successive values, starting at str and ending at String inclusive, passing each value in turn to the block.
 – The String.succ method is used to generate each value.

"a8".upto("b6") {|s| print s, ' ' } for s in "a8".."b6" print s, ' ' end produces: a8 a9 b0 b1 b2 b3 b4 b5 b6 a8 a9 b0 b1 b2 b3 b4 b5 b6
Time class → Time → Time (synonym)
Returns a Time object initialized to the current system time.
Note: The object created will be created using the resolution available on your system clock, and so may include fractional seconds.

a = #-> Sun Jun 09 00:19:20 CDT 2002 b = #-> Sun Jun 09 00:19:20 CDT 2002 a == b #-> false "%.6f" % a.to_f #-> "1023599960.526217" "%.6f" % b.to_f #-> "1023599960.526838"
time at, time_at Time ) → Time seconds [, microseconds ] ) → Time
Creates a new time object with the value given by Time, or the given number of seconds (and optional microseconds) from epoch.

at #-> Thu Jan 01 02:00:00 +0200 1970 #-> Sat Jan 01 07:00:00 +0200 2000 year [, month, day, hour, min, sec, usec] ) → Time sec, min, hour, day, month, year, wday, yday, isdst, tz ) → Time
Time.utc( year [, month, day, hour, min, sec, usec] ) → Time
Time.utc( sec, min, hour, day, month, year, wday, yday, isdst, tz ) → Time
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.

gm,"jan",1,20,15,1) #-> Sat Jan 01 20:15:01 UTC 2000
localtime, timelocal
Time.local( year [, month, day, hour, min, sec, usec] ) → Time
Time.local( sec, min, hour, day, month, year, wday, yday, isdst, tz ) → Time
Time.mktime( year [, month, day, hour, min, sec, usec] ) → Time (synonym)
Same as, but interprets the values in the local time zone.

Time.local(2000,"jan",1,20,15,1) #-> Sat Jan 01 20:15:01 CST 2000
Process.times → StructTms
Time.times → StructTms (obsolete)
Returns a Tms structure that contains user and system CPU times for this process.

t = Process.times puts [ t.utime, t.stime ] #-> [0.375, 0.218]
time + Numeric → Time
Addition. Adds some number of seconds (possibly fractional) to time and returns that value as a new time.
time - Time → Float 
time - Numeric → Time
Difference. Returns a new time that represents the difference between two times, or subtracts the given number of seconds in Numeric from time.
time <=> OtherTime → -1, 0, +1 
time <=> Numeric → -1, 0, +1
Comparison. Compares time with OtherTime or with Numeric, which is the number of seconds (possibly fractional) since epoch.

t = #-> Sun Nov 25 23:50:41 CST 2001 t + (60 * 60 * 24) #-> Mon Nov 26 23:50:41 CST 2001
t = #-> Sun Nov 25 23:50:41 CST 2001 t2 = t + 2592000 #-> Tue Dec 25 23:50:41 CST 2001 t2 - t #-> 2592000.0 t2 - 2592000 #-> Sun Nov 25 23:50:41 CST 2001
t = #-> Sun Nov 25 23:50:41 CST 2001 t2 = t + 2592000 #-> Tue Dec 25 23:50:41 CST 2001 t <=> t2 #-> -1 t2 <=> t #-> 1 t <=> t #-> 0
time.asctime → String 
time.ctime → String (Synonym)
Returns a canonical string representation of time.

asctime #-> "Sun Nov 25 23:50:41 2001"
time.gmtime → time
time.utc → time (Synonym)
Converts time to UTC (GMT), modifying the receiver.
time.gmt? → true or false
time.utc? → true or false (Synonym)
Returns true if time represents a time in UTC (GMT).

t = #-> Sun Nov 25 23:50:41 CST 2001 t.gmt? #-> false t.gmtime #-> Mon Nov 26 05:50:41 UTC 2001 t.gmt? #-> true
t = #-> Sun Nov 25 23:50:41 CST 2001 t.utc? #-> false t.utc #-> Mon Nov 26 05:50:41 UTC 2001 t.utc? #-> true
gmt?, utc?
t = #-> Sun Nov 25 23:50:41 CST 2001 t.gmt? #-> false t.utc? #-> false t =,"jan",1,20,15,1) #-> Sat Jan 01 20:15:01 UTC 2000 t.gmt? #-> true t.utc? #-> true
time.sec → Fixnum
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.

t = #-> Sun Nov 25 23:50:41 CST 2001 t.sec #-> 41
time.min → Fixnum
Returns the minute of the hour (0..59) for time.

t = #-> Sun Nov 25 23:50:41 CST 2001 t.min #-> 50
time.hour → Fixnum
Returns the hour of the day (0..23) for time.

t = #-> Sun Nov 25 23:50:41 CST 2001 t.hour #-> 23 → Fixnum
time.mday → Fixnum (Synonym)
Returns the day of the month (1..n) for time.

t = #-> Sun Nov 25 23:50:41 CST 2001 #-> 25
day of week, week day, weekday
time.wday → Fixnum 
Returns an integer representing the day of the week, 0..6, with Sunday == 0.

t = #-> Sun Nov 25 23:50:41 CST 2001 t.wday #-> 0
time.mon → Fixnum
time.month → Fixnum (Synonym)
Returns the month of the year (1..12) for time.

t = #-> Sat Mar 31 16:26:44 +0300 2007 t.mon #-> 3
time.year → Fixnum
Returns the year for time (including the century).

t = #-> Sun Nov 25 23:50:42 CST 2001 t.year #-> 2001
day of the year, day year, year day
time.yday → Fixnum
Returns an integer representing the day of the year, 1..366.

t = #-> Sun Nov 25 23:50:41 CST 2001 t.yday #-> 329 → String
Returns the name of the time zone used for time.

t =, "jan", 1, 20, 15, 1) #-> "GMT" t = Time.local(2000, "jan", 1, 20, 15, 1) #-> "CST"
time.isdst → true or false
Returns true if time occurs during Daylight Saving Time in its time zone.

t = Time.local(2000, 7, 1) #-> Sat Jul 01 00:00:00 CDT 2000 t.isdst #-> true t2 = Time.local(2000, 1, 1) #-> Sat Jan 01 00:00:00 CST 2000 t2.isdst #-> false
time.localtime → time
Converts time to local time (using the local time zone in effect for this process) modifying the receiver.

t =, "jan", 1, 20, 15, 1) t.gmt? #-> true t.localtime #-> Sat Jan 01 14:15:01 CST 2000 t.gmt? #-> false
date formatting, date output, date to string, print date
time.strftime( String ) → String
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.
Directives Format Meaning
%a –  The abbreviated weekday name ("Sun") 
%A –  The full weekday name ("Sunday") 
%b –  The abbreviated month name ("Jan") 
%B –  The full month name ("January") 
%c –  The preferred local date and time representation 
%dDay of the month (01..31) 
%HHour of the day, 24-hour clock (00..23) 
%IHour of the day, 12-hour clock (01..12) 
%jDay of the year (001..366) 
%mMonth of the year (01..12) 
%MMinute of the hour (00..59) 
%pMeridian indicator ("AM" or "PM") 
%SSecond of the minute (00..60) 
%UWeek number of the current year, starting with the first Sunday as the first day of the first week (00..53) 
%WWeek number of the current year, starting with the first Monday as the first day of the first week (00..53) 
%wDay 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 
%yYear without a century (00..99) 
%YYear with century (2011)
%Z –  Time zone name 
%% –  Literal "%" character

t = t.strftime("Printed on %m/%d/%Y") #-> "Printed on 11/25/2001" t.strftime("at %I:%M%p") #-> "at 11:50PM"
time.to_a → Array
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.

now = #-> Sun Nov 25 23:50:41 CST 2001 t = now.to_a #-> [41, 50, 23, 25, 11, 2001, 0, 329, false, "CST"]
time.to_f → Float
Returns the value of time as a floating point number of seconds since epoch.

t = "%10.5f" % t.to_f #-> "1006753841.72788" t.to_i #-> 1006753841
time.to_i → Integer
time.tv_sec → Integer (Synonym)
Returns the value of time as an integer number of seconds since epoch.

t = "%10.5f" % t.to_f #-> "1006753841.76503" t.to_i #-> 1006753841
time.usec → Integer  
time.tv_usec → Integer (Synonym)
Returns just the number of microseconds for time.

t = #-> Sun Nov 25 23:50:41 CST 2001 "%10.6f" % t.to_f #-> "1006753841.837830" t.usec #-> 837830
time.to_s → String
Returns a string representing time.
Equivalent to calling Time.strftime with a format string of "%a %b %d %H:%M:%S %Z %Y".

to_s #-> "Sun Nov 25 23:50:41 CST 2001"
2616 → String
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)

httpdate #-> Tue, 08 Jan 2008 07:49:30 GMT
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). year=-4712, mon=1, mday=1, sg=Date::ITALY) → aNewDate
Date.new3( year=-4712, mon=1, mday=1, sg=Date::ITALY) → aNewDate (Synonym)
Returns a Date for the given year, mon, and mday.
If mon is negative, it counts back from the end of the year.
If mday is negative, it counts back from the end of the month.
Date.new1( jd, sg=Date::ITALY) → aNewDate
Creates a Date corresponding to the given Julian day number.
Date.new2( year=-4712, yday=1, sg=Date::ITALY) → aNewDate
Returns a Date for the given year and yday.
If yday is negative, it counts back from the end of the year.
Date.neww( cyear=1582, cweek=41, cwday=5, sg=Date::ITALY) → aNewDate
Returns a Date for the given cyear, cweek, and cwday.
If cweek is negative, it counts back from the end of the year.
If cwday is negative, it counts back from the end of the week.

require 'date' d =, 3, 31) #-> #<Date: 2451635,2299161> [d.year, d.yday, d.wday] #-> [2000, 91, 5] [d.month, d.mday] #-> [3, 31] [d.cwyear, d.cweek, d.cwday] #-> [2000, 13, 5] [d.jd, d.mjd] #-> [2451635, 51634.5] (d << 1).to_s #-> "2000-02-29" d.succ.to_s #-> "2000-04-01" (d + 100).to_s #-> "2000-07-09" d.leap? #-> true, 3, -10).to_s #-> "2000-03-22" d1 =, 13, 7) #-> #<Date: 2451637,2299161> d1.to_s #-> "2000-04-02" [d1.cwday, d1.wday] #-> [7, 0] sg=Date::ITALY) → aNewDate
Returns a Date for today.

Date.exist?( year, mon, mday, sg=Date::ITALY) → jd
Converts a year, mon, and mday into a Julian day number, or nil if the parameters are invalid.
Date.exist2?( year, yday, sg=Date::ITALY) → jd
Converts a year and yday into a Julian day number, returning nil on error.
Date.existw?( cyear, cweek, cwday, sg=Date::ITALY) → jd
Converts a cyear, cweek, and cwday into a Julian day number.

leap year
Date.gregorian_leap?( year ) → true or false
Date.leap?( year ) → true or false (Synonym)
If year does not end with "00", returns true if year is divisible by 4, otherwise returns true if year is divisible by 400.
leap year
Date.julian_leap?( year ) → true or false
Returns true if year is divisible by 4.

The Math module contains module functions for basic trigonometric and transcendental functions.
E = 2.718281828 Value of e (base of natural logarithms)
PI = 3.141592654 Value of PI

Math.sqrt( Numeric ) → Float
Returns the non-negative square root of Numeric.
Raises ArgError if Numeric is less than zero.

Math.tan( Numeric ) → Float
Returns the tangent of Numeric (expressed in radians).
Math.atan2( y, x ) → Float
Computes the arc tangent given y and x.
Returns -PI..PI.

Math.sin( Numeric ) → Float
Computes the sine of Numeric (expressed in radians).
Returns -1..1.
Math.cos( Numeric ) → Float
Computes the cosine of Numeric (expressed in radians).
Returns -1..1.

Math.exp( Numeric ) → Float
Returns e raised to the power of Numeric.
Math.frexp( Numeric ) → Array
Returns a two-element array ([Float, Fixnum]) containing the normalized fraction and exponent of Numeric.
Math.ldexp( Float, Integer ) → Float
Returns the value of Float*2^Integer.

Math.log( Numeric ) → Float
Returns the natural logarithm of Numeric.
Math.log10( Numeric ) → Float
Returns the base 10 logarithm of Numeric.

Binding[context, environment]
binding → Binding
Returns a Binding object, describing the variable and method bindings at the point of call.
This object can be used when calling eval to execute the evaluated command in this environment.

def getBinding(param) return binding end b = getBinding("hello") eval "param", b #-> "hello"
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.

binding objects can be passed as the second argument of the Kernel.eval method, establishing an environment for the evaluation.
class Demo def initialize(n) @secret = n end def getBinding return binding() end end k1 = b1 = k1.getBinding k2 = b2 = k2.getBinding eval("@secret", b1) #-> 99 eval("@secret", b2) #-> -3 eval("@secret") #-> nil
Exception Variables
$! (Exception)
The exception object passed to raise.
$@ (Array)
The stack backtrace generated by the last exception.

Execution Environment Variables[global, variables, vars]
file path, load path, script path
$0 (String)
 – 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-line options 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 modules loaded by require
 – r/o

$$ (Fixnum)
 – The process number 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 library location, 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     record separator (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 -F flag.

cmd, stdin
$< (Object)
An object that provides access to the concatenation of the contents of all the files given as command-line arguments, 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 (IO)
The current standard error output.

$stdin (IO)
The current standard input.

$stdout (IO)
The current standard output.

Standard Objects
ARGF (Object)
A synonym for $<.
ARGV (Array)
A synonym for $*.

ENV (Object)
 – A hash-like object containing the program's environment variables.
 – 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".

true (TrueClass)
Singleton instance of class TrueClass
 – r/o
false (FalseClass)
Singleton instance of class FalseClass
 – r/o

nil (NilClass)
The singleton instance of class NilClass.
 – The value of uninitialized instance and global variables
 – r/o

self (Object)
The receiver (object) of the current method
 – r/o

Global Constants
If the main program file contains the directive __END__, then the constant DATA will be initialized so that reading from it will return lines following __END__ from the source file.

FALSE (FalseClass)
Synonym for false.
TRUE (TrueClass)
Synonym for true.

NIL (NilClass)
Synonym for nil.

The identifier of the platform running this program.
 – This string is in the same form as the platform identifier used by the GNU configure utility (which is not a coincidence).

The date of this release.

The version number of the interpreter.

The actual standard error stream for the program.
 – The initial value of $stderr.

The actual standard input stream for the program.
 – The initial value of $stdin.

The actual standard output stream for the program.
 – The initial value of $stdout.

A Binding object representing the binding at Ruby's top level — the level where programs are initially executed.

File class[File class, File., files]
close, new
file ="testfile", "r")
# ... process the file
You can create a File object that is open for reading, writing, or both, according to the mode string.
file open, file write,, open, open file, r, rw, w, write file"filename", "r|w|rw") do |file|
while line = file.gets
# ... process the file
The method also opens a file. In regular use, it behaves just like 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
Read file"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 command line, 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 testfile produces: This is line one This is line two This is line three
file, file.gets, reading
Invokes a block with the next 8-bit byte from the IO object
each line, eachline
.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.

each_line sample"testfile") do |file| file.each_line {|line| puts "Got #{line.dump}" } end produces: Got "This is line one\n" Got "This is line two\n" Got "This is line three\n" Got "And so on...\n"

each_byte sample"testfile") do |file| file.each_byte {|ch| putc ch; print "." } end produces: T.h.i.s. .i.s. .l.i.n.e. .o.n.e. .T.h.i.s. .i.s. .l.i.n.e. .t.w.o. .T.h.i.s. .i.s. .l.i.n.e. .t.h.r.e.e. .A.n.d. .s.o. .o.n....... .
file to string,
str ="testfile")
Read into string sample
str ="testfile") str.length #-> 66 str[0, 30] #-> "This is line one\nThis is line "
io.readlines, read lines, read_lines
arr = IO.readlines("testfile")
 – Read into an array
 – Don’t forget that I/O is never certain in an uncertain world — exceptions will be raised on most errors, and you should be ready to rescue them and take appropriate action.
IO.foreach("testfile") {|line| puts line }
This method takes the name of an I/O source, opens it for reading, calls the iterator once for every line in the file, and then closes the file automatically.

IO.readlines sample
arr = IO.readlines("testfile") arr.length #-> 4 arr[0] #-> "This is line one\n"
file, file.puts, writing
Write to file


binary data into a string
str1 = "\001\002\003" #-> "\001\002\003" str2 = "" str2 << 1 << 2 << 3 #-> "\001\002\003" [ 1, 2, 3 ].pack("c*") #-> "\001\002\003" pack255 = (0..255).to_a.pack("c*")'test.txt', 'w') do |file| file.print pack255 end
append an object to an output IO stream
endl = "\n" STDOUT << 99 << " red balloons" << endl produces: 99 red balloons
require 'stringio' ip ="now is\nthe time\nto learn\nRuby!") op ="", "w") ip.each_line do |line| op.puts line.reverse end op.string #-->"\nsi won\n\nemit eht\n\nnrael ot\n!ybuR\n"
File.size(fileName) → Integer
Returns the size of the file in bytes.

File.size("testfile") #->66
Writing UTF-8 file
Iconv.iconv(to, from, data) → Array
Iconv.iconv('UTF-8', '//IGNORE', data)
Iconv.iconv('UTF-8', 'CP1251', data)

UTF-8 outFile
require 'iconv', 'w') do |fp| source = $<.read begin out = Iconv.iconv('UTF-8', 'UTF-8', source) rescue out = Iconv.iconv('UTF-8', 'CP1251', source) end fp.puts(out) end

//IGNORE, 1251, cp-1251, cp1251, windows
Writing windows-1251 file'winText.txt', 'w') do |f| f.print Iconv.iconv('WINDOWS-1251//IGNORE', 'UTF-8', text) end
Dir class[Dir, Dir., Directory, folder]
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

About samples
The directory used in these examples contains the two regular files (config.h and main.rb), the parent directory (..), and the directory itself (.).
.chdir, change current directory, change directory, working directory
Dir.chdir([dirname]) → 0 | raises subclass of SystemCallError
Dir.chdir([dirname]) {|dirname| block } → value of the block
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.

Dir.chdir sample
Dir.chdir("/var/spool/mail") puts Dir.pwd Dir.chdir("/tmp") do puts Dir.pwd Dir.chdir("/usr") do puts Dir.pwd end puts Dir.pwd end puts Dir.pwd produces: /var/spool/mail /tmp /usr /tmp /var/spool/mail
.delete, .rmdir, .unlink, delete directory, delete folder, remove directory, unlink directory
Dir.delete(dirname) → 0 | raises subclass of SystemCallError
Deletes the named directory.

Raises a subclass of SystemCallError:
Directory not empty (Errno::ENOTEMPTY)
No such file or directory (Errno::ENOENT)

.entries, directory entries, files in directory, files list, subfolders
Dir.entries(dirname) → array | raises subclass of SystemCallError
Returns an array containing all of the filenames in the given directory. 

Will raise a SystemCallError if the named directory doesn’t exist.
No such file or directory (Errno::ENOENT)

Dir.entries sample
Dir.entries("testdir") #=> [".", "..", "config.h", "main.rb"]
.foreach, each dir entry, each folder entry
Dir.foreach(dirname) {|filename| block } → nil
Calls the block once for each entry in the named directory, passing the filename of each entry as a parameter to the block.

Dir.foreach sample
Dir.foreach("testdir") {|x| puts "Got #{x}" } produces: Got . Got .. Got config.h Got main.rb
.getwd, .gpwd, current directory, current folder, current path, working directory, working path
Dir.getwd → string
Dir.pwd (synonym)
Returns the path to the current working directory of this process as a string.

Dir.getwd sample
Dir.chdir("/tmp") Dir.getwd #=> "/tmp"
match files in directory, search files in folder
Dir.glob(pattern(s), [flags]) → array
Dir.glob(pattern(s), [flags]) {|filename| block } → nil

Dir[array] → array
Dir[string [, string ...]] → array
Equivalent to calling Dir.glob(array,0) and Dir.glob(,0).
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.

Dir.glob sample
Dir["config.?"] #=> ["config.h"] Dir.glob("config.?") #=> ["config.h"] Dir.glob("*.[a-z][a-z]") #=> ["main.rb"] Dir.glob("*.[^r]*") #=> ["config.h"] Dir.glob("*.{rb,h}") #=> ["main.rb", "config.h"] Dir.glob("*") #=> ["config.h", "main.rb"] Dir.glob("*", File::FNM_DOTMATCH) #=> [".", "..", "config.h", "main.rb"] rbfiles = File.join("**", "*.rb") Dir.glob(rbfiles) #=> ["main.rb", "lib/song.rb", "lib/song/karaoke.rb"] libdirs = File.join("**", "lib") Dir.glob(libdirs) #=> ["lib"] librbfiles = File.join("**", "lib", "**", "*.rb") Dir.glob(librbfiles) #=> ["lib/song.rb", "lib/song/karaoke.rb"] librbfiles = File.join("**", "lib", "*.rb") Dir.glob(librbfiles) #=> ["lib/song.rb"] 
.mkdir, create directory, create folder, folder permissions, new directory, new folder
Dir.mkdir(dirname [, integer]) → 0 | raises subclass of SystemCallError
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.

.new → dir → dir (synonym)
Returns a new directory object for the named directory.

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

change root, root
Dir.chroot(string) → 0
Changes this process’s idea of the file system root. Only a privileged process may make this call. 
Not available on all platforms. 
On Unix systems, see chroot for more information.

Dir.chroot sample
Dir.chdir("/production/secure/root") Dir.chroot("/production/secure/root") #-> 0 Dir.pwd #-> "/"
Enumerable: collect, detect, each_with_index, entries, find, find_all, grep, include?, map, max, member?, min, reject, select, sort, to_a

.close, close directory, close folder
dir.close → nil
Closes the directory stream. Any further attempts to access dir will raise an IOError.

dir ="testdir") #-> "." dir.close #-> nil # raises: closed directory (IOError)
each, entry, folder
dir.each {|filename| block } → dir
Calls the block once for each entry in this directory, passing the filename of each entry as a parameter to the block.

d ="testdir") d.each {|x| puts "Got #{x}" } produces: Got . Got .. Got config.h Got main.rb
folder describing
dir.inspect → string
Return a string describing of a Dir object.

dir ="testdir") dir.inspect #-> #<Dir:testdir>
.path, dir path, folder path
dir.path → string or nil
Returns the path parameter passed to dir's constructor.

dir ="testFolder/subfolder") p dir.path #-> "testFolder/subfolder"
.pos, folder read position
dir.pos → integer
Returns the current position in dir.

dir ="testFolder") p dir.pos #-> 0 p #-> "." p dir.pos #-> 1 p #-> ".." p dir.tell #-> 2
.seek, folder seek → dir
Seeks to a particular location in dir. integer must be a value returned by dir.tell or dir.pos

p dir ="testdir") #-> #<Dir:testdir> p #-> "." p i = dir.tell #-> 1 p #-> ".." p #-> #<Dir:testdir> p #-> ".."
dir, position, read, set
dir.pos = integer → integer
Synonym for, but returns the position parameter.

p dir ="testdir") #-> #<Dir:testdir> p #-> "." p i = dir.pos #-> 1 p #-> ".." p dir.pos #-> 2 p dir.pos = i #-> 1 p #-> ".."
folder entry, folder read, read folder → string or nil
Reads the next entry from dir and returns it as a string. Returns nil at the end of the stream.

dir ="testdir") p #-> "." p #-> ".." p #-> "config.h"
.rewind, rewind folder
dir.rewind → dir
Repositions dir to the first entry.

dir ="testdir") p #-> "." p dir.rewind #-> #<Dir:testdir> p #-> "."
ios.print([Object=$_ ]) → nil
print([Object=$_ ]) → nil
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.

$stdout.print("This is ", 100, " percent.\n") $\ = ',' print (1..3).to_a $_ = 'default' print produces: This is 100 percent. 123,default,
io.puts([Object]) → nil
puts([Object]) → 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.
Is shortcut for "puts obj.inspect"

$stdout.puts("first line", "second line") puts puts 777, 'end' p "p for puts" produces: first line second line 777 end p for puts
arr = [1, 2, 3] puts arr.inspect #-> [1, 2, 3] p arr #-> [1, 2, 3]
catch, try
... #process
rescue SomeErrorClass
... #handle some error
rescue SomeOtherErrorClass, SomeOtherErrorClass2 => localVariable
... #handle some other errors
... #handle all error
... #if no exceptions are raised
... #code that will always be executed
 – 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.
fail (Synonym)
raise "bad mp3 encoding"
raise InterfaceException, "Keyboard failure", caller
 – 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.
 Use the retry statement within a rescue clause to repeat the entire begin/end block.

Full sample with user error-class
class MyError < Exception attr :params def initialize(params) @params = params end end begin print 'Input: ' line = gets raise if line.chomp == 'des' raise{'repeat' => true}), "not Des :)" if line.chomp != 'Des' && line.chomp != '' rescue MyError => detail puts 'Not Des!' retry if detail.params['repeat'] rescue puts "it was 'des', game over" else puts 'else block' ensure puts 'ensure block' end
rescue and $!
op_file =, "w") begin # Exceptions raised by this code will # be caught by the following rescue clause while data = op_file.write(data) end rescue SystemCallError $stderr.print "IO failed: " + $! op_file.close File.delete(opfile_name) raise end
rescue to local variable
begin eval string rescue SyntaxError, NameError => boom print "String doesn't compile: " + boom rescue StandardError => bang print "Error running script: " + bang end
raise with parameters
raise raise "Missing name" if name.nil? if i >= names.size raise IndexError, "#{i} >= size (#{names.size})" end raise ArgumentError, "Name too big", caller
catch 'cachString' do
throw 'cachString'
 – 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.

skips puts 'arter while' if 'www' was typed
catch :myLabel do while line = gets throw :myLabel if line.chomp == 'www' break if line.chomp == '' end puts 'arter while' end puts "end"
catch with string
catch 'done' do while line = gets throw 'done' unless fields = line.split(/\t/) songlist.add(*fields)) end end
throw does not have to appear within the static scope of the catch
def prompt_and_get(prompt) print prompt res = readline.chomp throw :quit_requested if res == "!" res end catch :quit_requested do name = prompt_and_get("Name: ") age = prompt_and_get("Age: ") sex = prompt_and_get("Sex: ") # .. # process information end
Exception hierarchy
   fatal (used internally by Ruby)
         system-dependent exceptions (Errno::xxx)

Regular Expressions[RegExp]
//, case sensitivity, pattern, Regexp
%r{pattern}options 'pattern' [, options ] ) pattern [, options [ lang ] ] ) → Regexp
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::EXTENDEDIgnore spaces and newlines
Regexp::IGNORECASE – Matches are case insensitive
Regexp::POSIXLINE – Newlines treated as any other character
 – Otherwise, if options is not nil, the regexp will be case insensitive.
 – 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

r1 ='^a-z+:\\s+\w+') #-> /^a-z+:\s+\w+/ r2 =, true) #-> /^a-z+:\s+\w+/i r3 =, Regexp::EXTENDED) #-> /^a-z+:\s+\w+/x
Regexp creating
a ='^\s*[az]') #-> /^\s*[az]/ b = /^\s*[az]/ #-> /^\s*[az]/ c = %r{^\s*[az]} #-> /^\s*[az]/
regexp escape
Regexp.escape('we$xcg^456\sdg\s') #-> 'we\$xcg\^456\\sdg\\s'
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, the options are constants used as the second parameter of the constructor.
/i, case sensitivity
Case Insensitive.
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.
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.
Multiline Mode.
Normally, "." matches any character except a newline. With the /m option, "." matches any character.
Extended Mode.
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.

String matching
name = "Fats Waller" name =~ /a/ #-> 1 name != /z/ #-> true /a/ =~ name #-> 1 /a/.match(name) #-> MatchData object /z/.match(name) #-> nil m = /l+(.*)/.match(name) m.to_s #-> ller (whole match) m[1] #-> er (same as $1 when using =~)
$2, $3, $4, $5, $6, $7, $8
Regexp variables
$& – 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-global variables $~ 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.
 – 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.

Regexp variables
def show_regexp(a, re) if a =~ re "#{$`}<<#{$&}>>#{$'}" else "no match" end end show_regexp('very interesting', /t/) #-> very in<<t>>eresting show_regexp('Fats Waller', /a/) #-> F<<a>>ts Waller show_regexp('Fats Waller', /ll/) #-> Fats Wa<<ll>>er show_regexp('Fats Waller', /z/) #-> no match
"cat" =~ /(c|a)(t|z)/ # $+ will be set to "t"
end of line, end of string
 – 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 word boundaries and nonword boundaries, respectively.Word characters are letters, numbers, and underscores.

show_regexp("this is\nthe time", /^the/) #-> this is\n<<the>> time show_regexp("this is\nthe time", /is$/) #-> this <<is>>\nthe time show_regexp("this is\nthe time", /\Athis/) #-> <<this>> is\nthe time show_regexp("this is\nthe time", /\Athe/) #-> no match show_regexp("this is\nthe time", /\bis/) #-> this <<is>>\nthe time show_regexp("this is\nthe time", /\Bis/) #-> th<<is>> is\nthe time
Alternation   re1 | re2
 – Matches either the regular expression that precedes it or the regular expression that follows it.
 – There’s a trap for the unwary here, as | has a very low precedence.

Alternation sample
a = "red ball blue sky" show_regexp(a, /d|e/) #-> r<<e>>d ball blue sky show_regexp(a, /al|lu/) #-> red b<<al>>l blue sky show_regexp(a, /red ball|angry sky/) #-> <<red ball>> blue sky
\1, \2, \3, $1, $2, $3
Grouping (...)
 – 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.
You can combine regexpes together with the string interpolation mechanism. The included regexp will be surrounded by an uncapturing group.

show_regexp('banana', /an*/) #-> b<<an>>ana show_regexp('banana', /(an)*/) #-> <<>>banana show_regexp('banana', /(an)+/) #-> b<<anan>>a a = 'red ball blue sky' show_regexp(a, /blue|red/) #-> <<red>> ball blue sky show_regexp(a, /(blue|red) \w+/) #-> <<red ball>> blue sky show_regexp(a, /(red|blue) \w+/) #-> <<red ball>> blue sky show_regexp(a, /red|blue \w+/) #-> <<red>> ball blue sky show_regexp(a, /red (ball|angry) sky/) #-> no match a = 'the red angry sky' show_regexp(a, /red (ball|angry) sky/) #-> the <<red angry sky>>
show_regexp('banana', /an*/) #-> b<<an>>ana show_regexp('banana', /(an)*/) #-> <<>>banana show_regexp('banana', /(an)+/) #-> b<<anan>>a a = 'red ball blue sky' show_regexp(a, /blue|red/) #-> <<red>> ball blue sky show_regexp(a, /(blue|red) \w+/) #-> <<red ball>> blue sky show_regexp(a, /(red|blue) \w+/) #-> <<red ball>> blue sky show_regexp(a, /red|blue \w+/) #-> <<red>> ball blue sky show_regexp(a, /red (ball|angry) sky/) #-> no match a = 'the red angry sky' show_regexp(a, /red (ball|angry) sky/) #-> the <<red angry sky>>
$1, $2
special variables
"12:50am" =~ /(\d\d):(\d\d)(..)/ #-> 0 "Hour is #$1, minute #$2" #-> "Hour is 12, minute 50" "12:50am" =~ /((\d\d):(\d\d))(..)/ #-> 0 "Time is #$1" #-> "Time is 12:50" "Hour is #$2, minute #$3" #-> "Hour is 12, minute 50" "AM/PM is #$4" #-> "AM/PM is am"
using \1-\9
show_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.

Makes re into a group without 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 external
date = "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"]
Matches re at this point, but does not consume it (also known charmingly as "zero-width positive lookahead").
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"]
Matches if re does not match at this point.
Does not consume the match (zero-width negative lookahead).

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
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|"Normal:") { str =~ /a.*b.*a/ }"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
Turns on the corresponding "i", "m" or "x" option. If used inside a group, the effect is limited to that group.
?-i, ?-m, ?-x
Turns off the "i", "m", or "x" option.
?i:, ?m:, ?x:
Turns on the "i", "m", or "x" option for re.
?-i:, ?-m:, ?-x:
Turns off the "i", "m", or "x" option for re.

.sub(/pattern/, '*')
.gsub(/pattern/, '*')
.sub(/pattern/) {|match| ... }
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).

sub and gsub samples
a = "the quick brown fox" a.sub(/[aeiou]/, '*') #-> "th* quick brown fox" a.gsub(/[aeiou]/, '*') #-> "th* q**ck br*wn f*x" a.sub(/\s\S+/, '') #-> "the brown fox" a.gsub(/\s\S+/, '') #-> "the"
sub & gsub with block
a = "the quick brown fox" a.sub(/^./) {|match| match.upcase } #-> "The quick brown fox" a.gsub(/[aeiou]/) {|vowel| vowel.upcase } #-> "thE qUIck brOwn fOx"
sub & gsub with \
"fred:smith".sub(/(\w+):(\w+)/, '\2, \1') #-> "smith, fred" "nercpyitno".gsub(/(.)(.)/, '\2\1') #-> "encryption"
converting \ to \\
str = 'a\b\c' str.gsub(/\\/, '\\\\\\\\') #-> "a\\b\\c" str.gsub(/\\/, '\&\&') #-> "a\\b\\c" str.gsub(/\\/) { '\\\\' } #-> "a\\b\\c"
 – 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 $~.

MatchData, special variables
re = /(\d+):(\d+)/ # match a time hh:mm md = re.match("Time: 12:34am") md.class #-> MatchData md[0] #-> "12:34" (same as $&) md[1] #-> "12" (same as $1) md[2] #-> "34" (same as $2) md.pre_match #-> "Time: " (same as $`) md.post_match #-> "am" (same as $')
Two pattern matches available at the same time
re = /(\d+):(\d+)/ # match a time hh:mm md1 = re.match("Time: 12:34am") md2 = re.match("Time: 10:30pm") md1[1, 2] #-->["12", "34"] md2[1, 2] #-->["10", "30"]
re = /(\d+):(\d+)/ md1 = re.match("Time: 12:34am") md2 = re.match("Time: 10:30pm") [ $1, $2 ] # last successful match #-->["10", "30"] $~ = md1 [ $1, $2 ] # previous successful match #-->["12", "34"]
Character Classes
 – 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
Character class abbreviations
\d = [0-9] – Digit character
\D = [^0-9] – Nondigit
\s = [\s\t\r\n\f] – Whitespace character
\S = [^\s\t\r\n\f] – Nonwhitespace character
\w = [A-Za-z0-9_] – Word character
\W = [^A-Za-z0-9_] – Nonword character
POSIX Character Classes
[:alnum:] – Alphanumeric
[:alpha:] – Uppercase or lowercase letter
[:blank:] – Blank and tab
[:cntrl:] – Control characters (at least 0x00-0x1f, 0x7f)
[:digit:] – Digit
[:graph:] – Printable character excluding space
[:lower:] – Lowercase letter
[:print:] – Any printable character (including space)
[:punct:] – Printable character excluding space and alphanumeric
[:space:] – Whitespace (same as \s)
[:upper:] – Uppercase letter
[:xdigit:] – Hex digit (0-9, a-f, A-F)

Character Classes
show_regexp('Price $12.', /[aeiou]/) #-> Pr<<i>>ce $12. show_regexp('Price $12.', /[\s]/) #-> Price<< >>$12. show_regexp('Price $12.', /[[:digit:]]/) #-> Price $<<1>>2. show_regexp('Price $12.', /[[:space:]]/) #-> Price<< >>$12. show_regexp('Price $12.', /[[:punct:]aeiou]/) #-> Pr<<i>>ce $12. a = 'see [Design Patternspage 123]' show_regexp(a, /[A-F]/) #-> see [<<D>>esign Patternspage 123] show_regexp(a, /[A-Fa-f]/) #-> s<<e>>e [Design Patternspage 123] show_regexp(a, /[0-9]/) #-> see [Design Patternspage <<1>>23] show_regexp(a, /[0-9][0-9]/) #-> see [Design Patternspage <<12>>3] a = 'see [Design Pattern-spage 123]' show_regexp(a, /[]]/) #-> see [Design Pattern-spage 123<<]>> show_regexp(a, /[-]/) #-> see [Design Patterns<<->>page 123] show_regexp(a, /[^a-z]/) #-> see<< >>[Design Pattern-spage 123] show_regexp(a, /[^a-z\s]/) #-> see <<[>>Design Pattern-spage 123] a = 'It costs $12.' show_regexp(a, /c.s/) #-> It <<cos>>ts $12. show_regexp(a, /./) #-> <<I>>t costs $12. show_regexp(a, /\./) #-> It costs $12<<.>>
regexp, regular expressions, var in regexp, var regexp, variable in regexp, variables
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:

  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

str = "this string has ruby in it" re = "ruby" str =~ /#{Regexp.escape(re)}/ # => 16
a = 'ruby' b = 'on rails' str = "this string has ruby on rails in it" str.match(/#{a} #{b}/) # => true
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:

a = "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
Enumerable module[ENUMERABLE, lists]
array find
enumObj.find {|obj| block } → anObject or nil
enumObj.detect {|obj| block } → anObject or nil
Passes each entry in enumObj to block.
Returns the first for which block is not false.
Returns nil if no object matches.

[1,3,5,7,9].find { |i| i > 4 } #--> 5 @songs.find {|song| title == }
(1..10).detect {|i| i % 5 == 0 and i % 7 == 0 } #-> nil (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 } #-> 35
enumObj.find_all {|obj| block } → Array {|obj| block } → Array
Returns an array containing all elements of enumObj for which block is not false
remove all, remove_all, removeall
enumObj.reject {| obj | block } → Array
Returns an array for all elements of enumObj for which block is false.

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

.each, %w(
animals = %w( ant bee cat dog elk ) # create an array animals.each {|animal| puts animal } # iterate over the contents [ 'cat', 'dog', 'horse' ].each {|name| print name, " " } #-> cat dog horse ('a'..'e').each {|char| print char } #-> abcde
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.

puts [1,2,4].inject(0) {|sum, element| sum+element} #-> 0+1+2+4 = 7 puts [1,2,4].inject(1) {|product, element| product*element} #-> 1*1*2*4 = 8 #--or-- puts [1,2,4].inject {|sum, element| sum+element} #-> 1+2+4 = 7 puts [1,2,4].inject {|product, element| product*element} #-> 1*2*4 = 8
enumObj.sort → Array
enumObj.sort {|a, b| block } → Array
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.

Enumerable sort
%w(rhea kea flea).sort #-> ["flea", "kea", "rhea"] (1..10).sort {|a,b| b <=> a} #-> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
The following code sorts some files on modification time.
files = Dir["*"] sorted = files.sort {|a,b| File.mtime(a) <=> File.mtime(b)} sorted #-> ["mon", "tues", "wed", "thurs"]
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 a
sorted = Dir["*"].collect { |f| [test(?M, f), f] }.sort.collect { |f| f[1] } sorted #-> ["mon", "tues", "wed", "thurs"]
enumObj.collect {| obj | block } → Array {| obj | block } → Array (Synonym)
Returns a new array with the results of running block once for every element in enumObj.

(1..4).collect {|i| i*i} #-> [1, 4, 9, 16] (1..4).collect {"cat"} #-> ["cat", "cat", "cat", "cat"]
puts ["H", "A", "L"].collect {|x| x.succ } #-->["I", "B", "M"] number = 2 puts( (1..10).collect {|n| n*number }.join(", ") ) # or calc = lambda {|n| n*number } puts( (1..10).collect(&calc).join(", ") ) produces: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
each by index, each with index, each_by_index, with index
enumObj.each_with_index {| obj, i | block } → nil
Calls block with two arguments, the item and its index, for each item in enumObj.

hash = %w(cat dog wombat).each_with_index {|item, index| hash[item] = index } hash #-> {"cat"=>0, "wombat"=>2, "dog"=>1}
enumObj.to_a → Array
enumObj.entries → Array (Synonym)
Returns an array containing the items in enumObj.

(1..7).to_a #-> [1, 2, 3, 4, 5, 6, 7] { 'a'=>1, 'b'=>2, 'c'=>3 }.to_a #-> [["a", 1], ["b", 2], ["c", 3]]
enumObj.grep( pattern ) → Array
enumObj.grep( pattern ) {| obj | block } → Array
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.

(1..100).grep 38..44 #-> [38, 39, 40, 41, 42, 43, 44] c = IO.constants c.grep(/SEEK/) #-> ["SEEK_END", "SEEK_CUR", "SEEK_SET"] res = c.grep(/SEEK/) {|v| IO.const_get(v) } res #-> [2, 1, 0]
print ['Ru', 'dep', 'by'].grep(/^[^d]/) #-->Ruby"ordinal").grep(/d$/) do |line| puts line end produces: second third
arr include, array include
enumObj.include?( Object ) → true or false
enumObj.member?( Object ) → true or false (Synonym)
Returns true if any member of enumObj equals Object.
Equality is tested using ==.

IO.constants.include? "SEEK_SET" #-> true IO.constants.include? "SEEK_NO_FURTHER" #-> false
enumObj.max → Object
enumObj.max {| a,b | block } → Object
Returns the object in enumObj with the maximum value.
The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.
enumObj.min → Object
enumObj.min {| a,b | block } → Object
Returns the object in enumObj with the minimum value.
The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.

a = %w(albatross dog horse) a.max #-> "horse" a.max {|a,b| a.length <=> b.length } #-> "albatross"
a = %w(albatross dog horse) a.min #-> "albatross" a.min {|a,b| a.length <=> b.length } #-> "dog"
``, backquote, shell
`cmd` → String
Returns the standard output of running cmd in a subshell.
Command Expansion
 – 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 $?.
Redefining Backquotes
The string is passed to the method called Kernel.` (a single backquote). If you want, you can override this.

Command Expansion
`date` #-> "Sun Nov 25 23:50:57 CST 2001\n" `ls testdir`.split[1] #-> "main.rb" `ls`.split[34] #-> "book.out" %x{echo "Hello there"} #-> "Hello there\n"
Escape sequences in the command string
for i in 0..3 status = `dbmanager status id=#{i}` end
Redefining Backquotes
alias old_backquote ` def `(cmd) result = old_backquote(cmd) if $? != 0 fail "Command #{cmd} failed: #$?" end result end print `date` print `data` produces: Thu Aug 26 22:36:31 CDT 2004 prog.rb:10: command not found: data prog.rb:5:in ``': Command data failed: 32512 (RuntimeError) from prog.rb:10
select( readArray [, writeArray [ errorArray [timeout] ] ] ) → anArray or nil readArray [, writeArray [ errorArray [timeout] ] ] ) → anArray or nil
Performs a low-level select call, which waits for data to become available from input/output devices. The first three parameters are arrays of IO objects or nil. The last is a timeout in seconds, which should be an Integer or a Float. The call waits for data to become available for any of the IO objects in 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.

select( [$stdin], nil, nil, 1.5 ) # [[#<IO:0x401ba090>], [], []]
Integer(arg) → Integer
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

Integer(123.999) #-> 123 Integer("0x1a") #-> 26 Integer( #-> 1023599977 Integer("123") #-> 123 Integer("123.5") #-> invalid value for Integer: "123.5" (ArgumentError)
Float(arg) → Float
Returns arg converted to a float.
Numeric types are converted directly, nil is converted to 0.0, and the rest are converted using arg.to_f

Float(1) #-> 1.0 Float(nil) #-> 0.0 Float("123.456") #-> 123.456
String(arg) → String
Converts arg to a String by calling its to_s method.

String(self) #-> "main" String(self.type) #-> "Object" String(123456) #-> "123456"
Array(arg) → Array
Returns arg.to_a
Array Merge
Array merge return array

Array(1..5) #-> [1, 2, 3, 4, 5]
Array Merge
array1=[2,1,3] array2=[4,5,6] array3 = array1 | array2 #->[2,1,3,4,5,6]
Terminate execution immediately, effectively by calling Kernel.exit(1)

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

def do_at_exit(str1) at_exit { print str1 } end at_exit { puts "cruel world" } do_at_exit("goodbye ") exit produces: goodbye cruel world
autoload(Module, File) → nil
Registers File to be loaded (using Kernel::require ) the first time that Module (which may be a String or a symbol) is accessed.

autoload :MyModule, "/usr/local/lib/modules/my_module.rb"
binding → aBinding
Returns a Binding object, describing the variable and method bindings at the point of call. This object can be used when calling eval to execute the evaluated command in this environment.

def getBinding(param) return binding end b = getBinding("hello") eval "param", b #-> "hello"
block_given? → true or false
Returns true if yield would execute a block in the current context.

def try if block_given? yield else "no block" end end try #-> "no block" try { "hello" } #-> "hello" try do "hello" end
random, randomize, rnd
rand( max=0 ) → Number
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.

rand, srand
srand 1234 #-> 0 [rand, rand] #-> [0.7408769294, 0.2145348572] [rand(10), rand(1000)] #-> [3, 323] srand 1234 #-> 1234 [rand, rand] #-> [0.7408769294, 0.2145348572]
callcc {|cont| block } → Object
Generates a Continuation object, which it passes to the associated block. Performing a 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 Also see Kernel::throw for an alternative mechanism for unwinding a call stack.

caller( [Integer] ) → Array    
Returns the current execution stack – 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.

def a(skip) caller(skip) end def b(skip) a(skip) end def c(skip) b(skip) end c(0) #-> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"] c(1) #-> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"] c(2) #-> ["prog:8:in `c'", "prog:12"] c(3) #-> ["prog:13"]
catch( symbol ) {| | block } → Object
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 lexical scope.

def routine(n) puts n throw :done if n <= 0 routine(n-1) end catch(:done) { routine(3) } produces: 3 2 1 0
sprintf( aFormatString [, arguments ]*) → String
format( aFormatString [, arguments ]*) → String (Synonym)
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.

puts sprintf("%d %04x", 123, 123) #-> "123 007b" puts sprintf("%08b '%4s'", 123, 123) #-> "01111011 ' 123'" puts sprintf("%1$*2$s %2$d %1$s", "hello", 8) #-> " hello 8 hello" puts sprintf("%1$*2$s %2$d", "hello", -8) #-> "hello -8" puts sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #-> "+1.23: 1.23:1.23"
1250799.99 → 1'250'799.<u>99</u>$
v = 1250799.99 sprintf("%s.<u>%02d</u>$", v.to_i.to_s.gsub(/(\d)(?=\d{3}$|\d{6}$)/, '\1\''), v*100%100) produces: 1'250'799.<u>99</u>$
format, sprintf
academic example of sprintf
puts 'Some gibberish which is' puts format("%4$s%5$s%6$s%1$s%3$s%2$s", 'ame', 'ein', ' v', 'i', 'n th', 'e s') puts 'but which is definitely not...' puts format("...%2$s%4$s%6$s%1$s%4$s%1$s%3$s%5$s%7$s!", 'oo', 'co', ' po', 'd', 'e', 'e v', 'try').upcase
ios.printf(format_string [, obj, ...] ) → nil
Formats and writes to ios

printf("%.2f MB / %d MB (%.f%%)", 12.75, 80.533, 0.1583201917226*100) produces: 12.75 MB / 80 MB (16%)
Useful libs[libraries]
formatter print, p, pretty print, pretty-print
Returns nil
Pretty-printer for Ruby objects.

Non-pretty-printed output by p is:
#<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>

Pretty-printed output by pp you can see in the sample → 

Output Customization
To define your customized pretty printing function for your classes, redefine a method #pretty_print(pp) in the class. It takes an argument pp which is an instance of the class PP. The method should use PP#text, PP#breakable, PP#nest, PP#group and PP#pp to print the object. 


Author: Tanaka Akira

require 'pp' someObj = pp someObj produces: #<PP:0x2dea558 @buffer=[], @buffer_width=0, @genspace=#<Proc:0x02dd4178@C:/Ruby/lib/ruby/1.8/prettyprint.rb:84>, @group_queue= #<PrettyPrint::GroupQueue:0x2dbcf40 @queue= [[#<PrettyPrint::Group:0x2dbcf88 @break=false, @breakables=[], @depth=0>]]>, @group_stack= [#<PrettyPrint::Group:0x2dbcf88 @break=false, @breakables=[], @depth=0>], @indent=0, @maxwidth=79, @newline="\n", @output="", @output_width=0>
.scanf, formatted input, formatted read, input, read
scanf( aFormatString ) → Array
aString.scanf( aFormatString ) → Array
anIO.scanf( aFormatString ) → Array
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.

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.

Matches an optionally signed decimal integer.

Same as d.

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.

Matches an optionally signed octal integer.

Matches an optionally signed hexadecimal integer,

Matches an optionally signed floating-point number.

Matches a sequence of non-white-space character. The input string stops at white space or at the maximum field width, whichever occurs first.

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).

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

String#scanf and IO#scanf take a single argument (a format string)
require 'scanf' aString = "1abc2de 3fgh wer" array = aString.scanf("%d%s") p array #--> [1, "abc2de"] anIO = $stdin array = anIO.scanf("%d%s") # input> 123dfg p array #--> [123, "dfg"]
Kernel#scanf reads from STDIN
require 'scanf' array = scanf("%d%s") # input> 123fgj p array #--> [123, "fgj"]
Block usage
require 'scanf' str = "123 abc 456 def 789 ghi" p str.scanf("%d%s") { |num, str| [ num * 2, str.upcase ] } produces: [[246, "ABC"], [912, "DEF"], [1578, "GHI"]]

SHA encryption in Ruby
require 'digest/sha1' puts Digest::SHA1.hexdigest('something secret') #--> 9f6829bec931f53e2f24c2170e74e2fec2634153 require 'digest/sha2' puts Digest::SHA2.hexdigest('something secret') #--> 32bb6c32d66ddd132ae2c1d326fe1d75872830e45853b99e4449558225186dd1
CGI.escapeElement( String [, elements ]* ) → NewString
Returns a string made from the given argument with certain HTML-special characters escaped.
The HTML elements given in elements will be escaped; other HTML elements will not be affected.
CGI.unescapeElement( String [, elements ]* ) → NewString
Returns a string with the selected escaped HTML elements expanded to the actual characters.

escape tags, tags
print CGI::escapeElement('<BR><A HREF="url"></A><P>', "A", "IMG") produces: <BR>&lt;A HREF=&quot;url&quot;&gt;&lt;/A&gt;<P>
CGI.escapeHTML( String ) → NewString
Returns a string made from the given argument with HTML-special characters (such as "&",""","<",">") quoted using "&amp;", "&quot;", "&lt;", "&gt;", and so on.
CGI.unescapeHTML( String ) → NewString
Returns a string made from the given argument with HTML-special quoted characters expanded to the actual characters.

CGI.escape( String ) → NewString
Returns a URL-encoded string made from the given argument, where unsafe characters (not alphanumeric, "_", "-", or ".") are encoded using "%xx" escapes.
CGI.unescape( String ) → NewString
Returns a string containing "unsafe" characters made from the given URL-encoded argument, where unsafe characters were encoded using "%" escapes.

CGI.pretty( HTMLString, LeaderString=" " ) → Session
Formats the given 'HTMLString' in a nice, readable format, optionally prefixing each line with 'LeaderString'.

CGI.parse( String ) → Hash
Parses a query string and returns a hash of its key-value pairs.

CGI.rfc1123_date( Time ) → String
Returns a string representing the given time according to RFC 1123.

require 'CGI' puts CGI::rfc1123_date( ) produces: Wed, 21 Mar 2007 12:52:50 GMT
Ruby + mySQL[connecting to mySQL, data base, database, db, mySQL gem, SQL, working with mySQL]
Ruby DBI, Tomita Masahiro
Common information and links
MySQL modules —

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 (

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

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

You can install MySQL/Ruby using the Ruby Gems 
packaging manager:

$ sudo gem install mysql

More to read: — Using MySQL With Ruby

library, library for parsing XML, parse, parsing, xml gem, XML generation, XML parsing
Solutions for parsing/generating XML with Ruby
List of solutions:
  LibXML —
  Chilkat Ruby XML Library —
  XMLParser —
  Nokogiri —
  Hpricot —

Here you can read some useful discussions:
 Which Ruby XML library would you recommend for a 2.4MB XML file? —
  libxml-ruby 0.8.0 Released: Ruby Gets Fast, Reliable XML Processing At Last —
  Parsing XML with Ruby —

This table will introduce you some of these solutions.

About samples
All samples below are based on reading file sitemap.xml which located in the same directory. File content: <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns:xsi="http://www.w3.…….itemap/0.9"> <url> <loc></loc> <priority>1.00</priority> <changefreq>weekly</changefreq> </url> </urlset>
Site, download —
Documentation —

This is a module to access to James Clark's XML Parser Toolkit "expat" ( from Ruby.
Supported versions of expat are 1.95.0 or later (

XMLParser sample
require 'xml/parser' require 'xml/dom/builder' parser = tree = parser.parse('sitemap.xml')) url_node = tree.getElementsByTagName('url')[0] allInnerNodes = url_node.getElementsByTagName('*') allInnerNodes.each do |node| puts "#{node.to_s}\n #{node.nodeName} = #{node.firstChild.nodeValue}" end produces: <loc></loc> loc = <priority>1.00</priority> priority = 1.00 <changefreq>weekly</changefreq> changefreq = weekly
Session.send( String, flags, [, to ] ) → Fixnum
Sends "String" over "Session".
If specified, "to" is a struct sockaddr specifying the recipient address.
"flags" are the sum or one or more of the MSG_ options.
Returns the number of characters sent.

TCPSocket[tcp socket], port)
Connect to a server.
Send message to connected server.
(Assuming that @socket is a previusly opened socket.)
Receives line from connected server.

Session.send( String, flags ) → Fixnum
Session.send( String, flags, hostName, port ) → Fixnum
The two-parameter form sends "String" on an existing connection.
The four-parameter form sends "String" to port on hostName.

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.


mail, send, send mail, smtp
Simple sending message
require 'net/smtp' myMess = <<END_OF_MESSAGE From: theFrom <> To: theTo <> Subject: mySubj Message body END_OF_MESSAGE Net::SMTP.start('localhost') do |smtp| smtp.send_message myMess, '', '', '' end
OptionParser[arguments, cmd, options, parse arguments, parsing]
require 'optparse'
File: lib/optparse.rb (standard library)
Author: Nobu Nakada
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.

- 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.

Example file for testing. options_parse_sample.rb source:
version = 'v1.0.0 (19.03.11)' require 'optparse' require 'ostruct' # The options specified on the command line will be collected in *options* # We set default values here options = options.libs = [] options.inplace = false options.transfer_type = :auto options.silent = false do |opts| # if no options passed — showing the help if (ARGV.length == 0) ARGV << '-h' end opts.banner = "\n Usage: options_parse_sample.rb [options]" opts.separator "\n Specific options:" # Option with mandatory argument opts.on("-r", "--require LIBNAME", "Require the LIBRARY before executing script") do |lib| options.libs << lib end # Optional argument; multi-line description opts.on("-i", "--inplace [EXTENSION]", "Edit ARGV files in place (make backup if EXTENSION supplied)", " Sample: -i rb or -i.rb", " Default: "+options.inplace.to_s) do |ext| options.inplace = true options.extension = ext || '' options.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot end # Cast "delay" argument to a Float opts.on("-d N", "--delay N", Float, "Delay N seconds before executing") do |n| options.delay = n end # List of arguments opts.on("--list x,y,z", Array, "Example list of arguments") do |list| options.list = list end # Optional argument with keyword completion opts.on("--type [TYPE]", [:text, :binary, :auto], "Select transfer type (text, binary, auto)", " Default: "+options.transfer_type.to_s) do |t| options.transfer_type = t if t end # Boolean switch opts.on("-s", "--[no-]silent", "Run silently", " Default: "+options.silent.to_s) do |v| options.silent = v end opts.separator " Common options:" # help opts.on_tail("-h", "--help", "Show this message") do puts opts exit end # version opts.on_tail("-v", "--version", "Show version") do |v| puts ' '+version exit end end.parse! p options
Running this file with options:
>options_parse_sample.rb --help >options_parse_sample.rb -help >options_parse_sample.rb -h >options_parse_sample.rb Usage: options_parse_sample.rb [options] Specific options: -r, --require LIBNAME Require the LIBRARY before executing script -i, --inplace [EXTENSION] Edit ARGV files in place (make backup if EXTENSION supplied) Sample: -i rb or -i.rb Default: false -d, --delay N Delay N seconds before executing --list x,y,z Example list of arguments --type [TYPE] Select transfer type (text, binary, auto) Default: auto -s, --[no-]silent Run silently Default: false Common options: -v, --version Show version -h, --help Show this message >options_parse_sample.rb -v v1.0.0 (19.03.11) >options_parse_sample.rb -r somelib >options_parse_sample.rb -rsomelib # options.libs=["somelib"] # without argument >options_parse_sample.rb -r … missing argument: -r (OptionParser::MissingArgument) >options_parse_sample.rb -i rb >options_parse_sample.rb -irb >options_parse_sample.rb -i.rb >options_parse_sample.rb --inplace rb # options.inplace=true, options.extension=".rb" >options_parse_sample.rb -d1 >options_parse_sample.rb --delay 1 # options.delay=1.0 >options_parse_sample.rb -d 1.7 # options.delay=1.7 # if string instead number >options_parse_sample.rb -d abc … invalid argument: -d abc (OptionParser::InvalidArgument) >options_parse_sample.rb --list x,y,z # options. list=["x", "y", "z"] # Optional argument with keyword completion >options_parse_sample.rb --type binary >options_parse_sample.rb --type bi # options.transfer_type=:binary # Boolean switch >options_parse_sample.rb -s >options_parse_sample.rb --silent # options.silent=true >options_parse_sample.rb --no-silent # options.silent=false # unexpected option >options_parse_sample.rb -s … invalid option: -s (OptionParser::InvalidOption)
Matrix class
For now we can only provide a link for the official documentation:

Take a part and create some block here.

Ruby is not Ruby on Rails[Rails]
I suppose you are looking for some Ruby on Rails (web framework written in Ruby language) stuff.
These keywords you will be able to find on the (not released yet):
label, link_to, login activerecord