ruby keywords

201
Programski jezik Ruby Keywords Popis i opis ključnih rijeći

Upload: markoosijek

Post on 09-Jul-2016

250 views

Category:

Documents


1 download

DESCRIPTION

Ruby Keywords

TRANSCRIPT

Page 1: Ruby Keywords

Programski jezik Ruby

Keywords Popis i opis ključnih rijeći

Page 2: Ruby Keywords

Keywords The following keywords are used by Ruby.

__ENCODING__

The script encoding of the current file. See Encoding. __LINE__

The line number of this keyword in the current file.

__FILE__

The path to the current file.

BEGIN

Runs before any other code in the current file. See miscellaneous syntax END

Runs after any other code in the current file. See miscellaneous syntax alias

Creates an alias between two methods (and other things). See modules

and classes syntax and

Short-circuit Boolean and with lower precedence than && begin

Starts an exception handling block. See exceptions syntax break

Leaves a block early. See control expressions syntax case

Starts a case expression. See control expressions syntax class

Creates or opens a class. See modules and classes syntax def

Defines a method. See methods syntax defined?

Returns a string describing its argument. See miscellaneous syntax do

Starts a block.

else

The unhandled condition in case, if and unless expressions. See control

expressions elsif

An alternate condition for an if expression. See control expressions

Page 3: Ruby Keywords

end

The end of a syntax block. Used by classes, modules, methods, exception

handling and control expressions.

ensure

Starts a section of code that is always run when an exception is raised.

See exception handling false

Boolean false. See literals for

A loop that is similar to using the each method. See control expressions if

Used for if and modifier if expressions. See control expressions in

Used to separate the iterable object and iterator variable in a for loop.

See control expressions module

Creates or opens a module. See modules and classes syntax next

Skips the rest of the block. See control expressions nil

A false value usually indicating “no value” or “unknown”. See literals not

Inverts the following boolean expression. Has a lower precedence than ! or

Boolean or with lower precedence than || redo

Restarts execution in the current block. See control expressions rescue

Starts an exception section of code in a begin block. See exception

handling retry

Retries an exception block. See exception handling return

Exits a method. See methods self

The object the current method is attached to. See methods super

Calls the current method in a superclass. See methods

Page 4: Ruby Keywords

then

Indicates the end of conditional blocks in control structures. See control

expressions true

Boolean true. See literals undef

Prevents a class or module from responding to a method call. See modules

and classes unless

Used for unless and modifier unless expressions. See control expressions until

Creates a loop that executes until the condition is true. See control

expressions when

A condition in a case expression. See control expressions while

Creates a loop that executes while the condition is true. See control

expressions yield

Starts execution of the block sent to the current method. See methods  

Page 5: Ruby Keywords

__ENCODING__

The script encoding of the current file. See Encoding.

__LINE__ The line number of this keyword in the current file.

__FILE__ The path to the current file.

class Encoding

An Encoding instance represents a character encoding usable in Ruby. It is defined as a

constant under the Encoding namespace. It has a name and optionally, aliases:

Encoding::ISO_8859_1.name

#=> "ISO-8859-1"

Encoding::ISO_8859_1.names

#=> ["ISO-8859-1", "ISO8859-1"]

Ruby methods dealing with encodings return or accept Encoding instances as arguments

(when a method accepts an Encoding instance as an argument, it can be passed

an Encoding name or alias instead).

"some string".encoding

#=> #<Encoding:UTF-8>

string = "some string".encode(Encoding::ISO_8859_1)

#=> "some string"

string.encoding

#=> #<Encoding:ISO-8859-1>

"some string".encode "ISO-8859-1"

#=> "some string"

Page 6: Ruby Keywords

Encoding::ASCII_8BIT is a special encoding that is usually used for a byte string, not a

character string. But as the name insists, its characters in the range of ASCII are considered as

ASCII characters. This is useful when you use ASCII-8BIT characters with other ASCII

compatible characters.

Changing an encoding

The associated Encoding of a String can be changed in two different ways.

First, it is possible to set the Encoding of a string to a new Encoding without changing the

internal byte representation of the string, with String#force_encoding. This is how you can tell

Ruby the correct encoding of a string.

string

#=> "R\xC3\xA9sum\xC3\xA9"

string.encoding

#=> #<Encoding:ISO-8859-1>

string.force_encoding(Encoding::UTF_8)

#=> "R\u00E9sum\u00E9"

Second, it is possible to transcode a string, i.e. translate its internal byte representation to

another encoding. Its associated encoding is also set to the other encoding.

See String#encode for the various forms of transcoding, and the Encoding::Converter class for

additional control over the transcoding process.

string

#=> "R\u00E9sum\u00E9"

string.encoding

#=> #<Encoding:UTF-8>

string = string.encode!(Encoding::ISO_8859_1)

#=> "R\xE9sum\xE9"

string.encoding

#=> #<Encoding::ISO-8859-1>

Script encoding

All Ruby script code has an associated Encoding which any String literal created in the source

code will be associated to.

Page 7: Ruby Keywords

The default script encoding is Encoding::UTF-8 after v2.0, but it can be changed by a magic

comment on the first line of the source code file (or second line, if there is a shebang line on

the first). The comment must contain the word coding or encoding, followed by a colon,

space and the Encoding name or alias:

# encoding: UTF-8

"some string".encoding

#=> #<Encoding:UTF-8>

The __ENCODING__ keyword returns the script encoding of the file which the keyword is

written:

# encoding: ISO-8859-1

__ENCODING__

#=> #<Encoding:ISO-8859-1>

ruby -K will change the default locale encoding, but this is not recommended. Ruby source

files should declare its script encoding by a magic comment even when they only depend on

US-ASCII strings or regular expressions.

Locale encoding

The default encoding of the environment. Usually derived from locale.

see ::locale_charmap, ::find('locale')

Filesystem encoding

The default encoding of strings from the filesystem of the environment. This is used for

strings of file names or paths.

see ::find('filesystem')

External encoding

Each IO object has an external encoding which indicates the encoding that Ruby will use to

read its data. By default Ruby sets the external encoding of an IO object to the default

external encoding. The default external encoding is set by locale encoding or the interpreter -

E option. ::default_external returns the current value of the external encoding.

Page 8: Ruby Keywords

ENV["LANG"]

#=> "UTF-8"

Encoding.default_external

#=> #<Encoding:UTF-8>

$ ruby -E ISO-8859-1 -e "p Encoding.default_external"

#<Encoding:ISO-8859-1>

$ LANG=C ruby -e 'p Encoding.default_external'

#<Encoding:US-ASCII>

The default external encoding may also be set through ::default_external=, but you should not

do this as strings created before and after the change will have inconsistent encodings. Instead

use ruby -E to invoke ruby with the correct external encoding.

When you know that the actual encoding of the data of an IO object is not the default external

encoding, you can reset its external encoding with IO#set_encoding or set it at IO object

creation (see IO.new options).

Internal encoding

To process the data of an IO object which has an encoding different from its external

encoding, you can set its internal encoding. Ruby will use this internal encoding to transcode

the data when it is read from the IO object.

Conversely, when data is written to the IO object it is transcoded from the internal encoding

to the external encoding of the IO object.

The internal encoding of an IO object can be set with IO#set_encoding or at IO object

creation (see IO.new options).

The internal encoding is optional and when not set, the Ruby default internal encoding is

used. If not explicitly set this default internal encoding is nil meaning that by default, no

transcoding occurs.

The default internal encoding can be set with the interpreter option -

E. ::default_internal returns the current internal encoding.

Page 9: Ruby Keywords

$ ruby -e 'p Encoding.default_internal'

nil

$ ruby -E ISO-8859-1:UTF-8 -e "p [Encoding.default_external, \

Encoding.default_internal]"

[#<Encoding:ISO-8859-1>, #<Encoding:UTF-8>]

The default internal encoding may also be set through ::default_internal=, but you should not

do this as strings created before and after the change will have inconsistent encodings. Instead

use ruby -E to invoke ruby with the correct internal encoding.

IO encoding example

In the following example a UTF-8 encoded string “Ru00E9sumu00E9” is transcoded for

output to ISO-8859-1 encoding, then read back in and transcoded to UTF-8:

string = "R\u00E9sum\u00E9"

open("transcoded.txt", "w:ISO-8859-1") do |io|

io.write(string)

end

puts "raw text:"

p File.binread("transcoded.txt")

puts

open("transcoded.txt", "r:ISO-8859-1:UTF-8") do |io|

puts "transcoded text:"

p io.read

end

While writing the file, the internal encoding is not specified as it is only necessary for reading.

While reading the file both the internal and external encoding must be specified to obtain the

correct result.

Page 10: Ruby Keywords

$ ruby t.rb

raw text:

"R\xE9sum\xE9"

transcoded text:

"R\u00E9sum\u00E9"

Public Class Methods

aliases -> {"alias1" => "orig1", "alias2" → "orig2", ...}

Returns the hash of available encoding alias and original encoding name.

Encoding.aliases

#=> {"BINARY"=>"ASCII-8BIT", "ASCII"=>"US-ASCII", "ANSI_X3.4-1986"=>"US-

ASCII",

"SJIS"=>"Shift_JIS", "eucJP"=>"EUC-JP", "CP932"=>"Windows-31J"}

compatible?(obj1, obj2) → enc or nil

Checks the compatibility of two objects.

If the objects are both strings they are compatible when they are concatenatable. The encoding

of the concatenated string will be returned if they are compatible, nil if they are not.

Encoding.compatible?("\xa1".force_encoding("iso-8859-1"), "b")

#=> #<Encoding:ISO-8859-1>

Encoding.compatible?(

"\xa1".force_encoding("iso-8859-1"),

"\xa1\xa1".force_encoding("euc-jp"))

#=> nil

If the objects are non-strings their encodings are compatible when they have an encoding and:

Either encoding is US-ASCII compatible

Page 11: Ruby Keywords

One of the encodings is a 7-bit encoding

default_external → enc

Returns default external encoding.

The default external encoding is used by default for strings created from the following

locations:

CSV

File data read from disk

SDBM

StringIO

Zlib::GzipReader

Zlib::GzipWriter

String#inspect

Regexp#inspect

While strings created from these locations will have this encoding, the encoding may not be

valid. Be sure to check String#valid_encoding?.

File data written to disk will be transcoded to the default external encoding when written.

The default external encoding is initialized by the locale or -E option.

default_external = enc

Sets default external encoding. You should not set ::default_external in ruby code as strings

created before changing the value may have a different encoding from strings created after the

value was changed., instead you should use ruby -E to invoke ruby with the correct

default_external.

See ::default_external for information on how the default external encoding is used.

default_internal → enc

Returns default internal encoding. Strings will be transcoded to the default internal encoding

in the following places if the default internal encoding is not nil:

CSV

Etc.sysconfdir and Etc.systmpdir

File data read from disk

File names from Dir

Integer#chr

Page 12: Ruby Keywords

String#inspect and Regexp#inspect

Strings returned from Readline

Strings returned from SDBM

Time#zone

Values from ENV

Values in ARGV including $PROGRAM_NAME

Additionally String#encode and String#encode! use the default internal encoding if no

encoding is given.

The locale encoding (__ENCODING__), not ::default_internal, is used as the encoding of

created strings.

::default_internal is initialized by the source file's internal_encoding or -E option.

default_internal = enc or nil

Sets default internal encoding or removes default internal encoding when passed nil. You

should not set ::default_internal in ruby code as strings created before changing the value may

have a different encoding from strings created after the change. Instead you should use ruby

-E to invoke ruby with the correct default_internal.

See ::default_internal for information on how the default internal encoding is used.

find(string) → enc

Search the encoding with specified name. name should be a string.

Encoding.find("US-ASCII") #=> #<Encoding:US-ASCII>

Names which this method accept are encoding names and aliases including following special

aliases

“external”

default external encoding

“internal”

default internal encoding

“locale”

locale encoding

“filesystem”

filesystem encoding

Page 13: Ruby Keywords

An ArgumentError is raised when no encoding with name.

Only Encoding.find("internal") however returns nil when no encoding named “internal”,

in other words, when Ruby has no default internal encoding.

list → [enc1, enc2, ...]

Returns the list of loaded encodings.

Encoding.list

#=> [#<Encoding:ASCII-8BIT>, #<Encoding:UTF-8>,

#<Encoding:ISO-2022-JP (dummy)>]

Encoding.find("US-ASCII")

#=> #<Encoding:US-ASCII>

Encoding.list

#=> [#<Encoding:ASCII-8BIT>, #<Encoding:UTF-8>,

#<Encoding:US-ASCII>, #<Encoding:ISO-2022-JP (dummy)>]

locale_charmap → string

Returns the locale charmap name. It returns nil if no appropriate information.

Debian GNU/Linux

LANG=C

Encoding.locale_charmap #=> "ANSI_X3.4-1968"

LANG=ja_JP.EUC-JP

Encoding.locale_charmap #=> "EUC-JP"

SunOS 5

LANG=C

Encoding.locale_charmap #=> "646"

LANG=ja

Encoding.locale_charmap #=> "eucJP"

The result is highly platform dependent. So ::find may cause an error. If you need some

encoding object even for unknown locale, ::find(“locale”) can be used.

name_list → ["enc1", "enc2", ...]

Page 14: Ruby Keywords

Returns the list of available encoding names.

Encoding.name_list

#=> ["US-ASCII", "ASCII-8BIT", "UTF-8",

"ISO-8859-1", "Shift_JIS", "EUC-JP",

"Windows-31J",

"BINARY", "CP932", "eucJP"]

Public Instance Methods

ascii_compatible? → true or false

Returns whether ASCII-compatible or not.

Encoding::UTF_8.ascii_compatible? #=> true

Encoding::UTF_16BE.ascii_compatible? #=> false

dummy? → true or false

Returns true for dummy encodings. A dummy encoding is an encoding for which character

handling is not properly implemented. It is used for stateful encodings.

Encoding::ISO_2022_JP.dummy? #=> true

Encoding::UTF_8.dummy? #=> false

inspect → string

Returns a string which represents the encoding for programmers.

Encoding::UTF_8.inspect #=> "#<Encoding:UTF-8>"

Encoding::ISO_2022_JP.inspect #=> "#<Encoding:ISO-2022-JP (dummy)>"

name → string

Returns the name of the encoding.

Encoding::UTF_8.name #=> "UTF-8"

names → array

Page 15: Ruby Keywords

Returns the list of name and aliases of the encoding.

Encoding::WINDOWS_31J.names #=> ["Windows-31J", "CP932", "csWindows31J"]

replicate(name) → encoding

Returns a replicated encoding of enc whose name is name. The new encoding should have the

same byte structure of enc. If name is used by another encoding, raise ArgumentError.

to_s → string

Returns the name of the encoding.

Encoding::UTF_8.name #=> "UTF-8"

Page 16: Ruby Keywords

-BEGIN Runs before any other code in the current file. See miscellaneous syntax

Miscellaneous Syntax

Ending an Expression Ruby uses a newline as the end of an expression. When ending a line with an

operator, open parentheses, comma, etc. the expression will continue.

You can end an expression with a ; (semicolon). Semicolons are most frequently

used with ruby -e.

Indentation Ruby does not require any indentation. Typically, ruby programs are indented two

spaces.

If you run ruby with warnings enabled and have an indentation mis-match, you will

receive a warning.

alias The alias keyword is most frequently used to alias methods. When aliasing a

method, you can use either its name or a symbol:

alias new_name old_name alias :new_name :old_name

For methods, Module#alias_method can often be used instead of alias.

You can also use alias to alias global variables:

$old = 0 alias $new $old p $new # prints 0

You may use alias in any scope.

Page 17: Ruby Keywords

undef The undef keyword prevents the current class from responding to calls to the named

methods.

undef my_method

You may use symbols instead of method names:

undef :my_method

You may undef multiple methods:

undef method1, method2

You may use undef in any scope. See also Module#undef_method defined? defined?

is a keyword that returns a string describing its argument:

p defined?(UNDEFINED_CONSTANT) # prints nil p defined?(RUBY_VERSION) # prints "constant" p defined?(1 + 1) # prints "method"

You don't need to use parenthesis with defined?, but they are recommended due to

the low precedence of defined?.

For example, if you wish to check if an instance variable exists and that the instance

variable is zero:

defined? @instance_variable && @instance_variable.zero?

This returns "expression", which is not what you want if the instance variable is not

defined.

@instance_variable = 1 defined?(@instance_variable) && @instance_variable.zero?

Adding parentheses when checking if the instance variable is defined is a better check. This correctly returns nil when the instance variable is not defined

and false when the instance variable is not zero.

Page 18: Ruby Keywords

Using the specific reflection methods such as instance_variable_defined? for

instance variables or const_defined? for constants is less error prone than using defined?.

BEGIN and END BEGIN defines a block that is run before any other code in the current file. It is typically

used in one-liners with ruby -e. Similarly END defines a block that is run after any

other code. BEGIN must appear at top-level and END will issue a warning when you use it inside a

method.

Here is an example:

BEGIN { count = 0 }

You must use { and } you may not use do and end.

Here is an example one-liner that adds numbers from standard input or any files in

the argument list:

ruby -ne 'BEGIN { count = 0 }; END { puts count }; count += gets.to_i'

 

Page 19: Ruby Keywords

-break Leaves a block early. See control expressions syntax

Control Expressions Ruby has a variety of ways to control execution. All the expressions described here

return a value.

For the tests in these control expressions, nil and false are false-values

and true and any other object are true-values. In this document “true” will mean

“true-value” and “false” will mean “false-value”.

if Expression The simplest if expression has two parts, a “test” expression and a “then”

expression. If the “test” expression evaluates to a true then the “then” expression is

evaluated.

Here is a simple if statement:

if true then puts "the test resulted in a true-value" end

This will print “the test resulted in a true-value”.

The then is optional:

if true puts "the test resulted in a true-value" end

This document will omit the optional then for all expressions as that is the most

common usage of if.

You may also add an else expression. If the test does not evaluate to true

the else expression will be executed:

if false puts "the test resulted in a true-value" else puts "the test resulted in a false-value" end

This will print “the test resulted in a false-value”.

Page 20: Ruby Keywords

You may add an arbitrary number of extra tests to an if expression using elsif.

An elsif executes when all tests above the elsif are false.

a = 1 if a == 0 puts "a is zero" elsif a == 1 puts "a is one" else puts "a is some other value" end

This will print “a is one” as 1 is not equal to 0. Since else is only executed when there

are no matching conditions. Once a condition matches, either the if condition or any elsif condition,

the if expression is complete and no further tests will be performed.

Like an if, an elsif condition may be followed by a then.

In this example only “a is one” is printed:

a = 1 if a == 0 puts "a is zero" elsif a == 1 puts "a is one" elsif a >= 1 puts "a is greater than or equal to one" else puts "a is some other value" end

The tests for if and elsif may have side-effects. The most common use of side-

effect is to cache a value into a local variable:

if a = object.some_value # do something to a end

The result value of an if expression is the last value executed in the expression.

Ternary if You may also write a if-then-else expression using ? and :. This ternary if:

input_type = gets =~ /hello/i ? "greeting" : "other"

Is the same as this if expression:

input_type = if gets =~ /hello/i "greeting" else

Page 21: Ruby Keywords

"other" end

While the ternary if is much shorter to write than the more verbose form, for

readability it is recommended that the ternary if is only used for simple conditionals.

Also, avoid using multiple ternary conditions in the same expression as this can be

confusing.

unless Expression The unless expression is the opposite of the if expression. If the value is false, the

“then” expression is executed:

unless true puts "the value is a false-value" end

This prints nothing as true is not a false-value.

You may use an optional then with unless just like if.

Note that the above unless expression is the same as:

if not true puts "the value is a false-value" end

Like an if expression you may use an else condition with unless:

unless true puts "the value is false" else puts "the value is true" end

This prints “the value is true” from the else condition.

You may not use elsif with an unless expression.

The result value of an unless expression is the last value executed in the expression.

Modifier if and unless if and unless can also be used to modify an expression. When used as a modifier

the left-hand side is the “then” expression and the right-hand side is the “test”

expression:

a = 0 a += 1 if a.zero?

Page 22: Ruby Keywords

p a

This will print 1.

a = 0 a += 1 unless a.zero? p a

This will print 0.

While the modifier and standard versions have both a “test” expression and a “then”

expression, they are not exact transformations of each other due to parse order. Here

is an example that shows the difference:

p a if a = 0.zero?

This raises the NameError “undefined local variable or method `a'”. When ruby parses this expression it first encounters a as a method call in the “then”

expression, then later it sees the assignment to a in the “test” expression and

marks a as a local variable.

When running this line it first executes the “test” expression, a = 0.zero?.

Since the test is true it executes the “then” expression, p a. Since the a in the body

was recorded as a method which does not exist the NameError is raised. The same is true for unless.

case Expression The case expression can be used in two ways.

The most common way is to compare an object against multiple patterns. The

patterns are matched using the +===+ method which is aliased to +==+ on Object.

Other classes must override it to give meaningful behavior.

SeeModule#=== and Regexp#=== for examples. Here is an example of using case to compare a String against a pattern:

case "12345" when /^1/ puts "the string starts with one" else puts "I don't know what the string starts with" end

Here the string "12345" is compared with /^1/ by calling /^1/ === "12345" which

returns true. Like the if expression, the first when that matches is executed and all

other matches are ignored.

Page 23: Ruby Keywords

If no matches are found, the else is executed.

The else and then are optional, this case expression gives the same result as the

one above:

case "12345" when /^1/ puts "the string starts with one" end

You may place multiple conditions on the same when:

case "2" when /^1/, "2" puts "the string starts with one or is '2'" end

Ruby will try each condition in turn, so first /^1/ === "2" returns false, then "2" ===

"2" returns true, so “the string starts with one or is '2'” is printed.

You may use then after the when condition. This is most frequently used to place the

body of the when on a single line.

case a

when 1, 2 then puts "a is one or two

when 3 then puts "a is three"

else puts "I don't know what a is"

end

The other way to use a case expression is like an if-elsif expression:

a = 2 case when a == 1, a == 2 puts "a is one or two" when a == 3 puts "a is three" else puts "I don't know what a is" end

Again, the then and else are optional.

The result value of a case expression is the last value executed in the expression.

Page 24: Ruby Keywords

while Loop The while loop executes while a condition is true:

a = 0 while a < 10 do p a a += 1 end p a

Prints the numbers 0 through 10. The condition a < 10 is checked before the loop is

entered, then the body executes, then the condition is checked again. When the

condition results in false the loop is terminated. The do keyword is optional. The following loop is equivalent to the loop above:

while a < 10 p a a += 1 end

The result of a while loop is nil unless break is used to supply a value.

until Loop The until loop executes while a condition is false:

a = 0 until a > 10 do p a a += 1 end p a

This prints the numbers 0 through 11. Like a while loop the condition a > 10 is

checked when entering the loop and each time the loop body executes. If the

condition is false the loop will continue to execute. Like a while loop, the do is optional.

Like a while loop, the result of an until loop is nil unless break is used.

Page 25: Ruby Keywords

for Loop The for loop consists of for followed by a variable to contain the iteration argument

followed by in and the value to iterate over using each. The do is optional:

for value in [1, 2, 3] do puts value end

Prints 1, 2 and 3.

Like while and until, the do is optional.

The for loop is similar to using each, but does not create a new variable scope.

The result value of a for loop is the value iterated over unless break is used.

The for loop is rarely used in modern ruby programs.

Modifier while and until Like if and unless, while and until can be used as modifiers:

a = 0 a += 1 while a < 10 p a # prints 10

until used as a modifier:

a = 0 a += 1 until a > 10 p a # prints 11

You can use begin and end to create a while loop that runs the body once before the

condition:

a = 0 begin a += 1 end while a < 10 p a # prints 10

Page 26: Ruby Keywords

If you don't use rescue or ensure, Ruby optimizes away any exception handling

overhead.

break Statement Use break to leave a block early. This will stop iterating over the items in values if

one of them is even:

values.each do |value| break if value.even? # ... end

You can also terminate from a while loop using break:

a = 0 while true do p a a += 1 break if a < 10 end p a

This prints the numbers 0 and 1.

break accepts a value that supplies the result of the expression it is “breaking” out of:

result = [1, 2, 3].each do |value| break value * 2 if value.even? end p result # prints 4

next Statement Use next to skip the rest of the current iteration:

result = [1, 2, 3].map do |value| next if value.even? value * 2 end p result # prints [2, nil, 6]

next accepts an argument that can be used the result of the current block iteration:

result = [1, 2, 3].map do |value| next value if value.even?

Page 27: Ruby Keywords

value * 2 end p result # prints [2, 2, 6]

redo Statement Use redo to redo the current iteration:

result = [] while result.length < 10 do result << result.length redo if result.last.even? result << result.length + 1 end p result

This prints [0, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]

In Ruby 1.8, you could also use retry where you used redo. This is no longer true,

now you will receive a SyntaxError when you use retry outside of a rescue block.

See Exceptions for proper usage of retry.

Flip-Flop The flip-flop is a rarely seen conditional expression. It's primary use is for processing text from ruby one-line programs used with ruby -n or ruby -p.

The form of the flip-flop is an expression that indicates when the flip-flop turns on, .. (or ...), then an expression that indicates when the flip-flop will turn off. While

the flip-flop is on it will continue to evaluate to true, andfalse when off.

Here is an example:

selected = [] 0.upto 10 do |value| selected << value if value==2..value==8 end p selected # prints [2, 3, 4, 5, 6, 7, 8]

In the above example, the on condition is n==2. The flip-flop is initially off (false) for 0

and 1, but becomes on (true) for 2 and remains on through 8. After 8 it turns off and

remains off for 9 and 10.

Page 28: Ruby Keywords

The flip-flop must be used inside a conditional such as if, while, unless, until etc.

including the modifier forms. When you use an inclusive range (..), the off condition is evaluated when the on

condition changes:

selected = [] 0.upto 5 do |value| selected << value if value==2..value==2 end p selected # prints [2]

Here, both sides of the flip-flop are evaluated so the flip-flop turns on and off only when value equals 2. Since the flip-flop turned on in the iteration it returns true.

When you use an exclusive range (...), the off condition is evaluated on the

following iteration:

selected = [] 0.upto 5 do |value| selected << value if value==2...value==2 end p selected # prints [2, 3, 4, 5]

Here, the flip-flop turns on when value equals 2, but doesn't turn off on the same

iteration. The off condition isn't evaluated until the following iteration and value will

never be two again.  

Page 29: Ruby Keywords

-and Short-circuit Boolean and with lower precedence than &&

-begin Starts an exception handling block. See exceptions syntax

Exception Handling Exceptions are rescued in a begin/end block:

begin # code that might raise rescue # handle exception end

If you are inside a method, you do not need to use begin or end unless you wish to

limit the scope of rescued exceptions:

def my_method # ... rescue # ... end

The same is true for a class or module.

You can assign the exception to a local variable by using => variable_name at the

end of the rescue line:

begin # ... rescue => exception warn exception.message raise # re-raise the current exception end

By default, StandardError and its subclasses are rescued. You can rescue a specific set of exception classes (and their subclasses) by listing them after rescue:

begin # ... rescue ArgumentError, NameError # handle ArgumentError or NameError end

Page 30: Ruby Keywords

You may rescue different types of exceptions in different ways:

begin # ... rescue ArgumentError # handle ArgumentError rescue NameError # handle NameError rescue # handle any StandardError end

The exception is matched to the rescue section starting at the top, and matches only

once. If an ArgumentError is raised in the begin section, it will not be handled in

the StandardError section.

You may retry rescued exceptions:

begin # ... rescue # do something that may change the result of the begin block retry end

Execution will resume at the start of the begin block, so be careful not to create an

infinite loop.

Inside a rescue block is the only valid location for retry, all other uses will raise

a SyntaxError. If you wish to retry a block iteration use redo. See Control

Expressions for details. To always run some code whether an exception was raised or not, use ensure:

begin # ... rescue # ... ensure # this always runs end

You may also run some code when an exception is not raised:

begin # ... rescue # ... else # this runs only when no exception was raised ensure # ... end

Page 31: Ruby Keywords

class Exception Descendants of class Exception are used to communicate

between Kernel#raise and rescue statements in begin ... end blocks. Exception objects

carry information about the exception – its type (the exception's class name), an optional

descriptive string, and optional traceback information. Exception subclasses may add

additional information like NameError#name.

Programs may make subclasses of Exception, typically of StandardError or RuntimeError, to

provide custom classes and add additional information. See the subclass list below for

defaults for raise and rescue.

When an exception has been raised but not yet handled

(in rescue, ensure, at_exit and END blocks) the global variable $! will contain the current

exception and $@ contains the current exception's backtrace.

It is recommended that a library should have one subclass

of StandardError or RuntimeError and have specific exception types inherit from it. This

allows the user to rescue a generic exception type to catch all exceptions the library may raise

even if future versions of the library add new exception subclasses.

For example:

class MyLibrary class Error < RuntimeError end class WidgetError < Error end class FrobError < Error end end

To handle both WidgetError and FrobError the library user can rescue MyLibrary::Error.

The built-in subclasses of Exception are:

NoMemoryError

ScriptError

o LoadError

o NotImplementedError

o SyntaxError

SecurityError

SignalException

o Interrupt

StandardError – default for rescue

o ArgumentError

UncaughtThrowError

Page 32: Ruby Keywords

o EncodingError

o FiberError

o IOError

EOFError

o IndexError

KeyError

StopIteration

o LocalJumpError

o NameError

NoMethodError

o RangeError

FloatDomainError

o RegexpError

o RuntimeError – default for raise

o SystemCallError

Errno::*

o ThreadError

o TypeError

o ZeroDivisionError

SystemExit

SystemStackError

fatal – impossible to rescue

Exception serialization/deserialization

Public Class Methods

exception(string) → an_exception or exc

With no argument, or if the argument is the same as the receiver, return the receiver.

Otherwise, create a new exception object of the same class as the receiver, but with a message

equal to string.to_str. json_create(object)

Deserializes JSON string by constructing new Exception object with message m and

backtrace b serialized with to_json new(msg = nil) → exception

Construct a new Exception object, optionally passing in a message.

Page 33: Ruby Keywords

Public Instance Methods

exc == obj → true or false

Equality—If obj is not an Exception, returns false. Otherwise,

returns true if exc and obj share same class, messages, and backtrace. as_json(*)

Returns a hash, that will be turned into a JSON object and represent this object. backtrace → array

Returns any backtrace associated with the exception. The backtrace is an array of strings, each

containing either “filename:lineNo: in `method''' or “filename:lineNo.''

def a raise "boom" end def b a() end begin b() rescue => detail print detail.backtrace.join("\n") end

produces:

prog.rb:2:in `a'

prog.rb:6:in `b'

prog.rb:10

backtrace_locations → array

Returns any backtrace associated with the exception. This method is similar to #backtrace, but

the backtrace is an array of

Thread::Backtrace::Location.

Now, this method is not affected by #set_backtrace. cause → an_exception or nil

Returns the previous exception ($!) at the time this exception was raised. This is useful for

wrapping exceptions and retaining the original exception information.

Page 34: Ruby Keywords

exception(string) → an_exception or exc

With no argument, or if the argument is the same as the receiver, return the receiver.

Otherwise, create a new exception object of the same class as the receiver, but with a message

equal to string.to_str. inspect → string

Return this exception's class name and message

message → string

Returns the result of invoking exception.to_s. Normally this returns the exception's

message or name. By supplying a to_str method, exceptions are agreeing to be used where

Strings are expected. set_backtrace(backtrace) → array

Sets the backtrace information associated with exc. The backtrace must be an array of String

objects or a single String in the format described in #backtrace. to_json(*args)

Stores class name (Exception) with message m and backtrace array b as JSON string to_s → string

Returns exception's message (or the name of the exception if no message is set).

Page 35: Ruby Keywords

-alias Creates an alias between two methods (and other things). See modules and classes syntax

 

Modules Modules serve two purposes in Ruby, namespacing and mix-in functionality.

A namespace can be used to organize code by package or functionality that

separates common names from interference by other packages. For example, the

IRB namespace provides functionality for irb that prevents a collision for the common

name “Context”.

Mix-in functionality allows sharing common methods across multiple classes or

modules. Ruby comes with the Enumerable mix-in module which provides many enumeration methods based on the each method andComparable allows comparison

of objects based on the <=> comparison method.

Note that there are many similarities between modules and classes. Besides the

ability to mix-in a module, the description of modules below also applies to classes.

Module Definition A module is created using the module keyword:

module MyModule # ... end

A module may be reopened any number of times to add, change or remove

functionality:

module MyModule def my_method end end module MyModule alias my_alias my_method end module MyModule remove_method :my_method end

Page 36: Ruby Keywords

Reopening classes is a very powerful feature of Ruby, but it is best to only reopen

classes you own. Reopening classes you do not own may lead to naming conflicts or

difficult to diagnose bugs.

Nesting Modules may be nested:

module Outer module Inner end end

Many packages create a single outermost module (or class) to provide a namespace

for their functionality.

You may also define inner modules using :: provided the outer modules (or classes)

are already defined:

module Outer::Inner::GrandChild end

Note that this will raise a NameError if Outer and Outer::Inner are not already

defined.

This style has the benefit of allowing the author to reduce the amount of indentation.

Instead of 3 levels of indentation only one is necessary. However, the scope of

constant lookup is different for creating a namespace using this syntax instead of the

more verbose syntax.

Scope

self self refers to the object that defines the current scope. self will change when

entering a different method or when defining a new module.

Constants

Accessible constants are different depending on the module nesting (which syntax was used to define the module). In the following example the constant A::Z is

accessible from B as A is part of the nesting:

Page 37: Ruby Keywords

module A Z = 1 module B p Module.nesting #=> [A::B, A] p Z #=> 1 end end

However, if you use :: to define A::B without nesting it inside A,

a NameError exception will be raised because the nesting does not include A:

module A Z = 1 end module A::B p Module.nesting #=> [A::B] p Z #=> raises NameError end

If a constant is defined at the top-level you may preceded it with :: to reference it:

Z = 0 module A Z = 1 module B p ::Z #=> 0 end end

Methods

For method definition documentation see the syntax documentation for methods.

Class methods may be called directly. (This is slightly confusing, but a method on a

module is often called a “class method” instead of a “module method”. See

also Module#module_function which can convert an instance method into a class

method.)

When a class method references a constant, it uses the same rules as referencing it

outside the method as the scope is the same.

Instance methods defined in a module are only callable when included. These

methods have access to the constants defined when they were included through the

ancestors list:

module A Z = 1 def z Z end

Page 38: Ruby Keywords

end include A p self.class.ancestors #=> [Object, A, Kernel, BasicObject] p z #=> 1

Visibility

Ruby has three types of visibility. The default is public. A public method may be

called from any other object. The second visibility is protected. When calling a protected method the sender must

be a subclass of the receiver or the receiver must be a subclass of the sender.

Otherwise a NoMethodError will be raised. Protected visibility is most frequently used to define == and other comparison

methods where the author does not wish to expose an object's state to any caller and

would like to restrict it only to inherited classes.

Here is an example:

class A def n(other) other.m end end class B < A def m 1 end protected :m end class C < B end a = A.new b = B.new c = C.new c.n b #=> 1 -- C is a subclass of B b.n b #=> 1 -- m called on defining class a.n b # raises NoMethodError A is not a subclass of B

The third visibility is private. A private method may not be called with a receiver, not

even self. If a private method is called with a receiver a NoMethodError will be

raised.

Page 39: Ruby Keywords

alias and undef You may also alias or undefine methods, but these operations are not restricted to

modules or classes. See the miscellaneous syntax section for documentation.

Classes Every class is also a module, but unlike modules a class may not be mixed-in to

another module (or class). Like a module, a class can be used as a namespace. A

class also inherits methods and constants from its superclass.

Defining a class Use the class keyword to create a class:

class MyClass # ... end

If you do not supply a superclass your new class will inherit from Object. You may inherit from a different class using < followed by a class name:

class MySubclass < MyClass # ... end

There is a special class BasicObject which is designed as a blank class and includes

a minimum of built-in methods. You can use BasicObject to create an independent

inheritance structure. See the BasicObjectdocumentation for further details.

Inheritance Any method defined on a class is callable from its subclass:

class A Z = 1 def z Z end end class B < A end

Page 40: Ruby Keywords

p B.new.z #=> 1

The same is true for constants:

class A Z = 1 end class B < A def z Z end end p B.new.z #=> 1

You can override the functionality of a superclass method by redefining the method:

class A def m 1 end end class B < A def m 2 end end p B.new.m #=> 2

If you wish to invoke the superclass functionality from a method use super:

class A def m 1 end end class B < A def m 2 + super end end p B.new.m #=> 3

When used without any arguments super uses the arguments given to the subclass

method. To send no arguments to the superclass method use super(). To send

specific arguments to the superclass method provide them manually like super(2).

super may be called as many times as you like in the subclass method.

Page 41: Ruby Keywords

Singleton Classes The singleton class (also known as the metaclass or eigenclass) of an object is a

class that holds methods for only that instance. You can access the singleton class of an object using class << object like this:

class C end class << C # self is the singleton class here end

Most frequently you'll see the singleton class accessed like this:

class C class << self # ... end end

This allows definition of methods and attributes on a class (or module) without needing to write def self.my_method.

Since you can open the singleton class of any object this means that this code block:

o = Object.new def o.my_method 1 + 1 end

is equivalent to this code block:

o = Object.new class << o def my_method 1 + 1 end end

Both objects will have a my_method that returns 2.  

 

 

 

 

 

Page 42: Ruby Keywords

class Module A Module is a collection of methods and constants. The methods in a module may be instance

methods or module methods. Instance methods appear as methods in a class when the module

is included, module methods do not. Conversely, module methods may be called without

creating an encapsulating object, while instance methods may not.

(See Module#module_function.)

In the descriptions that follow, the parameter sym refers to a symbol, which is either a quoted

string or a Symbol (such as :name).

module Mod include Math CONST = 1 def meth # ... end end Mod.class #=> Module Mod.constants #=> [:CONST, :PI, :E] Mod.instance_methods #=> [:meth]

Public Class Methods

constants → array constants(inherited) → array In the first form, returns an array of the names of all constants accessible from the point of

call. This list includes the names of all modules and classes defined in the global scope.

Module.constants.first(4) # => [:ARGF, :ARGV, :ArgumentError, :Array] Module.constants.include?(:SEEK_SET) # => false class IO Module.constants.include?(:SEEK_SET) # => true end

The second form calls the instance method constants.

nesting → array Returns the list of Modules nested at the point of call.

module M1 module M2 $a = Module.nesting end end $a #=> [M1::M2, M1] $a[0].name #=> "M1::M2"

Page 43: Ruby Keywords

new → mod new {|mod| block } → mod Creates a new anonymous module. If a block is given, it is passed the module object, and the

block is evaluated in the context of this module using module_eval.

fred = Module.new do def meth1 "hello" end def meth2 "bye" end end a = "my string" a.extend(fred) #=> "my string" a.meth1 #=> "hello" a.meth2 #=> "bye"

Assign the module to a constant (name starting uppercase) if you want to treat it like a regular

module.

Public Instance Methods

mod < other → true, false, or nil Returns true if mod is a subclass of other. Returns nil if there's no relationship between the

two. (Think of the relationship in terms of the class definition: “class A<B” implies “A<B”.)

mod <= other → true, false, or nil Returns true if mod is a subclass of other or is the same as other. Returns nil if there's no

relationship between the two. (Think of the relationship in terms of the class definition: “class

A<B” implies “A<B”.)

module <=> other_module → -1, 0, +1, or nil Comparison—Returns -1, 0, +1 or nil depending on whether module includes other_module,

they are the same, or if module is included by other_module.

Returns nil if module has no relationship with other_module, if other_module is not a

module, or if the two values are incomparable.

obj == other → true or false equal?(other) → true or false eql?(other) → true or false Equality — At the Object level, == returns true only if obj and other are the same object.

Typically, this method is overridden in descendant classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses as it is used to

determine object identity (that is, a.equal?(b) if and only if a is the same object as b):

obj = "a" other = obj.dup obj == other #=> true

Page 44: Ruby Keywords

obj.equal? other #=> false obj.equal? obj #=> true

The eql? method returns true if obj and other refer to the same hash key. This is used

by Hash to test members for equality. For objects of class Object, eql? is synonymous

with ==. Subclasses normally continue this tradition by aliasing eql? to their

overridden == method, 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

mod === obj → true or false Case Equality—Returns true if obj is an instance of mod or and instance of one of mod's

descendants. Of limited use for modules, but can be used in case statements to classify

objects by class.

mod > other → true, false, or nil Returns true if mod is an ancestor of other. Returns nil if there's no relationship between the

two. (Think of the relationship in terms of the class definition: “class A<B” implies “B>A”.)

mod >= other → true, false, or nil Returns true if mod is an ancestor of other, or the two modules are the same. Returns nil if

there's no relationship between the two. (Think of the relationship in terms of the class

definition: “class A<B” implies “B>A”.)

ancestors → array Returns a list of modules included/prepended in mod (including mod itself).

module Mod include Math include Comparable prepend Enumerable end Mod.ancestors #=> [Enumerable, Mod, Comparable, Math] Math.ancestors #=> [Math] Enumerable.ancestors #=> [Enumerable]

autoload(module, filename) → nil Registers filename to be loaded (using Kernel::require) the first time that module (which

may be a String or a symbol) is accessed in the namespace of mod.

module A end A.autoload(:B, "b") A::B.doit # autoloads "b"

autoload?(name) → String or nil

Page 45: Ruby Keywords

Returns filename to be loaded if name is registered as autoload in the namespace of mod.

module A end A.autoload(:B, "b") A.autoload?(:B) #=> "b"

class_eval(string [, filename [, lineno]]) → obj Evaluates the string or block in the context of mod, except that when a block is given,

constant/class variable lookup is not affected. This can be used to add methods to a

class. module_eval returns the result of evaluating its argument. The

optional filename and lineno parameters set the text for error messages.

class Thing end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123)

produces:

Hello there!

dummy:123:in `module_eval': undefined local variable

or method `code' for Thing:Class

class_exec(arg...) {|var...| block } → obj Evaluates the given block in the context of the class/module. The method defined in the block

will belong to the receiver. Any arguments passed to the method will be passed to the block.

This can be used if the block needs to access instance variables.

class Thing end Thing.class_exec{ def hello() "Hello there!" end } puts Thing.new.hello()

produces:

Hello there!

class_variable_defined?(symbol) → true or false class_variable_defined?(string) → true or false Returns true if the given class variable is defined in obj. String arguments are converted to

symbols.

class Fred

Page 46: Ruby Keywords

@@foo = 99 end Fred.class_variable_defined?(:@@foo) #=> true Fred.class_variable_defined?(:@@bar) #=> false

class_variable_get(symbol) → obj class_variable_get(string) → obj Returns the value of the given class variable (or throws a NameError exception). The @@ part

of the variable name should be included for regular class variables. String arguments are

converted to symbols.

class Fred @@foo = 99 end Fred.class_variable_get(:@@foo) #=> 99

class_variable_set(symbol, obj) → obj class_variable_set(string, obj) → obj Sets the class variable named by symbol to the given object. If the class variable name is

passed as a string, that string is converted to a symbol.

class Fred @@foo = 99 def foo @@foo end end Fred.class_variable_set(:@@foo, 101) #=> 101 Fred.new.foo #=> 101

class_variables(inherit=true) → array Returns an array of the names of class variables in mod. This includes the names of class

variables in any included modules, unless the inherit parameter is set to false.

class One @@var1 = 1 end class Two < One @@var2 = 2 end One.class_variables #=> [:@@var1] Two.class_variables #=> [:@@var2, :@@var1] Two.class_variables(false) #=> [:@@var2]

const_defined?(sym, inherit=true) → true or false const_defined?(str, inherit=true) → true or false Says whether mod or its ancestors have a constant with the given name:

Float.const_defined?(:EPSILON) #=> true, found in Float itself Float.const_defined?("String") #=> true, found in Object (ancestor) BasicObject.const_defined?(:Hash) #=> false

Page 47: Ruby Keywords

If mod is a Module, additionally Object and its ancestors are checked:

Math.const_defined?(:String) #=> true, found in Object

In each of the checked classes or modules, if the constant is not present but there is an

autoload for it, true is returned directly without autoloading:

module Admin autoload :User, 'admin/user' end Admin.const_defined?(:User) #=> true

If the constant is not found the callback const_missing is not called and the method

returns false.

If inherit is false, the lookup only checks the constants in the receiver:

IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor) IO.const_defined?(:SYNC, false) #=> false, not found in IO itself

In this case, the same logic for autoloading applies.

If the argument is not a valid constant name a NameError is raised with the message “wrong

constant name name”:

Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar

const_get(sym, inherit=true) → obj const_get(str, inherit=true) → obj Checks for a constant with the given name in mod. If inherit is set, the lookup will also

search the ancestors (and Object if mod is a Module).

The value of the constant is returned if a definition is found, otherwise a NameError is raised.

Math.const_get(:PI) #=> 3.14159265358979

This method will recursively look up constant names if a namespaced class name is provided.

For example:

module Foo; class Bar; end end Object.const_get 'Foo::Bar'

The inherit flag is respected on each lookup. For example:

module Foo class Bar VAL = 10 end class Baz < Bar; end end Object.const_get 'Foo::Baz::VAL' # => 10

Page 48: Ruby Keywords

Object.const_get 'Foo::Baz::VAL', false # => NameError

If the argument is not a valid constant name a NameError will be raised with a warning

“wrong constant name”.

Object.const_get 'foobar' #=> NameError: wrong constant name foobar

const_missing(sym) → obj Invoked when a reference is made to an undefined constant in mod. It is passed a symbol for

the undefined constant, and returns a value to be used for that constant. The following code is

an example of the same:

def Foo.const_missing(name) name # return the constant name as Symbol end Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned

In the next example when a reference is made to an undefined constant, it attempts to load a

file whose name is the lowercase version of the constant (thus class Fred is assumed to be in

file fred.rb). If found, it returns the loaded class. It therefore implements an autoload feature

similar to Kernel#autoload and #autoload.

def Object.const_missing(name) @looked_for ||= {} str_name = name.to_s raise "Class not found: #{name}" if @looked_for[str_name] @looked_for[str_name] = 1 file = str_name.downcase require file klass = const_get(name) return klass if klass raise "Class not found: #{name}" end

const_set(sym, obj) → obj const_set(str, obj) → obj Sets the named constant to the given object, returning that object. Creates a new constant if no

constant with the given name previously existed.

Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714 Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968

If sym or str is not a valid constant name a NameError will be raised with a warning “wrong

constant name”.

Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar

constants(inherit=true) → array

Page 49: Ruby Keywords

Returns an array of the names of the constants accessible in mod. This includes the names of

constants in any included modules (example at start of section), unless the inherit parameter is

set to false.

The implementation makes no guarantees about the order in which the constants are yielded.

IO.constants.include?(:SYNC) #=> true IO.constants(false).include?(:SYNC) #=> false

Also see Module::const_defined?.

deprecate_constant(*args)

freeze → mod Prevents further modifications to mod.

This method returns self.

include(module, ...) → self Invokes Module.append_features on each parameter in reverse order.

include?(module) → true or false Returns true if module is included in mod or one of mod's ancestors.

module A end class B include A end class C < B end B.include?(A) #=> true C.include?(A) #=> true A.include?(A) #=> false

included_modules → array Returns the list of modules included in mod.

module Mixin end module Outer include Mixin end Mixin.included_modules #=> [] Outer.included_modules #=> [Mixin]

inspect() Alias for: to_s

instance_method(symbol) → unbound_method Returns an UnboundMethod representing the given instance method in mod.

Page 50: Ruby Keywords

class Interpreter def do_a() print "there, "; end def do_d() print "Hello "; end def do_e() print "!\n"; end def do_v() print "Dave"; end Dispatcher = { "a" => instance_method(:do_a), "d" => instance_method(:do_d), "e" => instance_method(:do_e), "v" => instance_method(:do_v) } def interpret(string) string.each_char {|b| Dispatcher[b].bind(self).call } end end interpreter = Interpreter.new interpreter.interpret('dave')

produces:

Hello there, Dave!

instance_methods(include_super=true) → array Returns an array containing the names of the public and protected instance methods in the

receiver. For a module, these are the public and protected methods; for a class, they are the

instance (not singleton) methods. If the optional parameter is false, the methods of any

ancestors are not included.

module A def method1() end end class B include A def method2() end end class C < B def method3() end end A.instance_methods(false) #=> [:method1] B.instance_methods(false) #=> [:method2] B.instance_methods(true).include?(:method1) #=> true C.instance_methods(false) #=> [:method3] C.instance_methods.include?(:method2) #=> true

method_defined?(symbol) → true or false method_defined?(string) → true or false Returns true if the named method is defined by mod (or its included modules and, if mod is a

class, its ancestors). Public and protected methods are matched. String arguments are

converted to symbols.

module A def method1() end def protected_method1() end

Page 51: Ruby Keywords

protected :protected_method1 end class B def method2() end def private_method2() end private :private_method2 end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.method_defined? "method1" #=> true C.method_defined? "method2" #=> true C.method_defined? "method3" #=> true C.method_defined? "protected_method1" #=> true C.method_defined? "method4" #=> false C.method_defined? "private_method2" #=> false

module_eval {|| block } → obj Evaluates the string or block in the context of mod, except that when a block is given,

constant/class variable lookup is not affected. This can be used to add methods to a

class. module_eval returns the result of evaluating its argument. The

optional filename and lineno parameters set the text for error messages.

class Thing end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123)

produces:

Hello there!

dummy:123:in `module_eval': undefined local variable

or method `code' for Thing:Class

module_exec(arg...) {|var...| block } → obj Evaluates the given block in the context of the class/module. The method defined in the block

will belong to the receiver. Any arguments passed to the method will be passed to the block.

This can be used if the block needs to access instance variables.

class Thing end Thing.class_exec{ def hello() "Hello there!" end } puts Thing.new.hello()

Page 52: Ruby Keywords

produces:

Hello there!

name → string Returns the name of the module mod. Returns nil for anonymous modules.

prepend(module, ...) → self Invokes Module.prepend_features on each parameter in reverse order.

private_class_method(symbol, ...) → mod private_class_method(string, ...) → mod Makes existing class methods private. Often used to hide the default constructor new.

String arguments are converted to symbols.

class SimpleSingleton # Not thread safe private_class_method :new def SimpleSingleton.create(*args, &block) @me = new(*args, &block) if ! @me @me end end

private_constant(symbol, ...) → mod Makes a list of existing constants private.

private_instance_methods(include_super=true) → array Returns a list of the private instance methods defined in mod. If the optional parameter

is false, the methods of any ancestors are not included.

module Mod def method1() end private :method1 def method2() end end Mod.instance_methods #=> [:method2] Mod.private_instance_methods #=> [:method1]

private_method_defined?(symbol) → true or false private_method_defined?(string) → true or false Returns true if the named private method is defined by _ mod_ (or its included modules and,

if mod is a class, its ancestors). String arguments are converted to symbols.

module A def method1() end end class B private def method2() end end class C < B include A def method3() end

Page 53: Ruby Keywords

end A.method_defined? :method1 #=> true C.private_method_defined? "method1" #=> false C.private_method_defined? "method2" #=> true C.method_defined? "method2" #=> false

protected_instance_methods(include_super=true) → array Returns a list of the protected instance methods defined in mod. If the optional parameter

is false, the methods of any ancestors are not included.

protected_method_defined?(symbol) → true or false protected_method_defined?(string) → true or false Returns true if the named protected method is defined by mod (or its included modules and,

if mod is a class, its ancestors). String arguments are converted to symbols.

module A def method1() end end class B protected def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.protected_method_defined? "method1" #=> false C.protected_method_defined? "method2" #=> true C.method_defined? "method2" #=> true

psych_yaml_as(url) Also aliased as: yaml_as

public_class_method(symbol, ...) → mod public_class_method(string, ...) → mod Makes a list of existing class methods public.

String arguments are converted to symbols.

public_constant(symbol, ...) → mod Makes a list of existing constants public.

public_instance_method(symbol) → unbound_method Similar to instance_method, searches public method only.

public_instance_methods(include_super=true) → array Returns a list of the public instance methods defined in mod. If the optional parameter

is false, the methods of any ancestors are not included.

public_method_defined?(symbol) → true or false

Page 54: Ruby Keywords

public_method_defined?(string) → true or false Returns true if the named public method is defined by mod (or its included modules and,

if mod is a class, its ancestors). String arguments are converted to symbols.

module A def method1() end end class B protected def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.public_method_defined? "method1" #=> true C.public_method_defined? "method2" #=> false C.method_defined? "method2" #=> true

remove_class_variable(sym) → obj Removes the definition of the sym, returning that constant's value.

class Dummy @@var = 99 puts @@var remove_class_variable(:@@var) p(defined? @@var) end

produces:

99 nil

singleton_class? → true or false Returns true if mod is a singleton class or false if it is an ordinary class or module.

class C end C.singleton_class? #=> false C.singleton_class.singleton_class? #=> true

to_s → string Returns a string representing this module or class. For basic classes and modules, this is the

name. For singletons, we show information on the thing we're attached to as well.

Also aliased as: inspect

yaml_as(url) Alias for: psych_yaml_as

Page 55: Ruby Keywords

Private Instance Methods

alias_method(new_name, old_name) → self Makes new_name a new copy of the method old_name. This can be used to retain access to

methods that are overridden.

module Mod alias_method :orig_exit, :exit def exit(code=0) puts "Exiting with code #{code}" orig_exit(code) end end include Mod exit(99)

produces:

Exiting with code 99

append_features(mod) → mod When this module is included in another, Ruby calls append_features in this module,

passing it the receiving module in mod. Ruby's default implementation is to add the constants,

methods, and module variables of this module to mod if this module has not already been

added to mod or one of its ancestors. See also Module#include.

attr(*args)

attr_accessor(symbol, ...) → nil attr_accessor(string, ...) → nil Defines a named attribute for this module, where the name is symbol.id2name, creating an

instance variable (@name) and a corresponding access method to read it. Also creates a method

called name= to set the attribute. String arguments are converted to symbols.

module Mod attr_accessor(:one, :two) end Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]

attr_reader(symbol, ...) → nil attr(symbol, ...) → nil attr_reader(string, ...) → nil attr(string, ...) → nil Creates instance variables and corresponding methods that return the value of each instance

variable. Equivalent to calling “attr:name'' on each name in turn. String arguments are

converted to symbols.

attr_writer(symbol, ...) → nil attr_writer(string, ...) → nil

Page 56: Ruby Keywords

Creates an accessor method to allow assignment to the attribute symbol.id2name. String

arguments are converted to symbols.

define_method(symbol, method) → symbol define_method(symbol) { block } → symbol Defines an instance method in the receiver. The method parameter can be a Proc, a Method or

an UnboundMethod object. If a block is specified, it is used as the method body. This block is

evaluated using instance_eval, a point that is tricky to demonstrate

because define_method is private. (This is why we resort to the send hack in this example.)

class A def fred puts "In Fred" end def create_method(name, &block) self.class.send(:define_method, name, &block) end define_method(:wilma) { puts "Charge it!" } end class B < A define_method(:barney, instance_method(:fred)) end a = B.new a.barney a.wilma a.create_method(:betty) { p self } a.betty

produces:

In Fred Charge it! #<B:0x401b39e8>

extend_object(obj) → obj 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 puts "Can't add Picky to a String" else puts "Picky added to #{o.class}" super end end end (s = Array.new).extend Picky # Call Object.extend (s = "quick brown fox").extend Picky

produces:

Picky added to Array

Page 57: Ruby Keywords

Can't add Picky to a String

extended(othermod) The equivalent of included, but for extended modules.

module A def self.extended(mod) puts "#{self} extended in #{mod}" end end module Enumerable extend A end # => prints "A extended in Enumerable"

included(othermod) Callback invoked whenever the receiver is included in another module or class. This should

be used in preference to Module.append_features if your code wants to perform some

action when a module is included in another.

module A def A.included(mod) puts "#{self} included in #{mod}" end end module Enumerable include A end # => prints "A included in Enumerable"

method_added(method_name) Invoked as a callback whenever an instance method is added to the receiver.

module Chatty def self.method_added(method_name) puts "Adding #{method_name.inspect}" end def self.some_class_method() end def some_instance_method() end end

produces:

Adding :some_instance_method

method_removed(method_name) Invoked as a callback whenever an instance method is removed from the receiver.

module Chatty def self.method_removed(method_name) puts "Removing #{method_name.inspect}" end

Page 58: Ruby Keywords

def self.some_class_method() end def some_instance_method() end class << self remove_method :some_class_method end remove_method :some_instance_method end

produces:

Removing :some_instance_method

method_undefined(p1) Not documented

module_function(symbol, ...) → self module_function(string, ...) → self Creates module functions for the named methods. These functions may be called with the

module as a receiver, and also become available as instance methods to classes that mix in the

module. Module functions are copies of the original, and so may be changed independently.

The instance-method versions are made private. If used with no arguments, subsequently

defined methods become module functions. String arguments are converted to symbols.

module Mod def one "This is one" end module_function :one end class Cls include Mod def call_one one end end Mod.one #=> "This is one" c = Cls.new c.call_one #=> "This is one" module Mod def one "This is the new one" end end Mod.one #=> "This is one" c.call_one #=> "This is the new one"

prepend_features(mod) → mod When this module is prepended in another, Ruby calls prepend_features in this module,

passing it the receiving module in mod. Ruby's default implementation is to overlay the

constants, methods, and module variables of this module to mod if this module has not already

been added to mod or one of its ancestors. See also Module#prepend.

prepended(othermod)

Page 59: Ruby Keywords

The equivalent of included, but for prepended modules.

module A def self.prepended(mod) puts "#{self} prepended to #{mod}" end end module Enumerable prepend A end # => prints "A prepended to Enumerable"

private → self private(symbol, ...) → self private(string, ...) → self With no arguments, sets the default visibility for subsequently defined methods to private.

With arguments, sets the named methods to have private visibility. String arguments are

converted to symbols.

module Mod def a() end def b() end private def c() end private :a end Mod.private_instance_methods #=> [:a, :c]

protected → self protected(symbol, ...) → self protected(string, ...) → self With no arguments, sets the default visibility for subsequently defined methods to protected.

With arguments, sets the named methods to have protected visibility. String arguments are

converted to symbols.

public → self public(symbol, ...) → self public(string, ...) → self With no arguments, sets the default visibility for subsequently defined methods to public.

With arguments, sets the named methods to have public visibility. String arguments are

converted to symbols.

refine(klass) { block } → module Refine klass in the receiver.

Returns an overlaid module.

remove_const(sym) → obj Removes the definition of the given constant, returning that constant's previous value. If that

constant referred to a module, this will not change that module's name and can lead to

confusion.

Page 60: Ruby Keywords

remove_method(symbol) → self remove_method(string) → self Removes the method identified by symbol from the current class. For an example,

see Module.undef_method. String arguments are converted to symbols.

undef_method(symbol) → self undef_method(string) → self Prevents the current class from responding to calls to the named method. Contrast this

with remove_method, which deletes the method from the particular class; Ruby will still

search superclasses and mixed-in modules for a possible receiver. String arguments are

converted to symbols.

class Parent def hello puts "In parent" end end class Child < Parent def hello puts "In child" end end c = Child.new c.hello class Child remove_method :hello # remove from child, still in parent end c.hello class Child undef_method :hello # prevent any calls to 'hello' end c.hello

produces:

In child

In parent

prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError)

using(module) → self Import class refinements from module into the current class or module definition.

module Singleton The Singleton module implements the Singleton pattern.

Page 61: Ruby Keywords

Usage To use Singleton, include the module in your class.

class Klass include Singleton # ... end

This ensures that only one instance of Klass can be created.

a,b = Klass.instance, Klass.instance a == b # => true Klass.new # => NoMethodError - new is private ...

The instance is created at upon the first call of Klass.instance().

class OtherKlass include Singleton # ... end ObjectSpace.each_object(OtherKlass){} # => 0 OtherKlass.instance ObjectSpace.each_object(OtherKlass){} # => 1

This behavior is preserved under inheritance and cloning.

Implementation This above is achieved by:

Making Klass.new and Klass.allocate private.

Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that

the Singleton properties are kept when inherited and cloned.

Providing the Klass.instance() method that returns the same object each time it is

called.

Overriding Klass._load(str) to call Klass.instance().

Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent cloning or

duping.

Singleton and Marshal

Page 62: Ruby Keywords

By default Singleton's #_dump(depth) returns the empty string. Marshalling by default will

strip state information, e.g. instance variables and taint state, from the instance. Classes

using Singleton can provide custom _load(str) and _dump(depth) methods to retain some of

the previous state of the instance.

require 'singleton' class Example include Singleton attr_accessor :keep, :strip def _dump(depth) # this strips the @strip information from the instance Marshal.dump(@keep, depth) end def self._load(str) instance.keep = Marshal.load(str) instance end end a = Example.instance a.keep = "keep this" a.strip = "get rid of this" a.taint stored_state = Marshal.dump(a) a.keep = nil a.strip = nil b = Marshal.load(stored_state) p a == b # => true p a.keep # => "keep this" p a.strip # => nil

Public Class Methods

_load()

By default calls instance(). Override to retain singleton state.

Private Class Methods

append_features(mod)

Calls superclass method

included(klass)

Calls superclass method

Page 63: Ruby Keywords

Public Instance Methods

_dump(depth = -1)

By default, do not retain any state when marshalling.

clone()

Raises a TypeError to prevent cloning. dup()

Raises a TypeError to prevent duping.  

Page 64: Ruby Keywords

-END Runs after any other code in the current file. See miscellaneous syntax

Miscellaneous Syntax

Ending an Expression Ruby uses a newline as the end of an expression. When ending a line with an

operator, open parentheses, comma, etc. the expression will continue.

You can end an expression with a ; (semicolon). Semicolons are most frequently

used with ruby -e.

Indentation Ruby does not require any indentation. Typically, ruby programs are indented two

spaces.

If you run ruby with warnings enabled and have an indentation mis-match, you will

receive a warning.

alias The alias keyword is most frequently used to alias methods. When aliasing a

method, you can use either its name or a symbol:

alias new_name old_name alias :new_name :old_name

For methods, Module#alias_method can often be used instead of alias.

You can also use alias to alias global variables:

$old = 0 alias $new $old p $new # prints 0

You may use alias in any scope.

Page 65: Ruby Keywords

undef The undef keyword prevents the current class from responding to calls to the named

methods.

undef my_method

You may use symbols instead of method names:

undef :my_method

You may undef multiple methods:

undef method1, method2

You may use undef in any scope. See also Module#undef_method

defined? defined? is a keyword that returns a string describing its argument:

p defined?(UNDEFINED_CONSTANT) # prints nil p defined?(RUBY_VERSION) # prints "constant" p defined?(1 + 1) # prints "method"

You don't need to use parenthesis with defined?, but they are recommended due to

the low precedence of defined?.

For example, if you wish to check if an instance variable exists and that the instance

variable is zero:

defined? @instance_variable && @instance_variable.zero?

This returns "expression", which is not what you want if the instance variable is not

defined.

@instance_variable = 1 defined?(@instance_variable) && @instance_variable.zero?

Adding parentheses when checking if the instance variable is defined is a better check. This correctly returns nil when the instance variable is not defined

and false when the instance variable is not zero.

Page 66: Ruby Keywords

Using the specific reflection methods such as instance_variable_defined? for

instance variables or const_defined? for constants is less error prone than using defined?.

BEGIN and END BEGIN defines a block that is run before any other code in the current file. It is typically

used in one-liners with ruby -e. Similarly END defines a block that is run after any

other code. BEGIN must appear at top-level and END will issue a warning when you use it inside a

method.

Here is an example:

BEGIN { count = 0 }

You must use { and } you may not use do and end.

Here is an example one-liner that adds numbers from standard input or any files in

the argument list:

ruby -ne 'BEGIN { count = 0 }; END { puts count }; count += gets.to_i'

 

Page 67: Ruby Keywords

-def Defines a method. See methods syntax

-return Exits a method. See methods

-self The object the current method is attached to. See methods

-super Calls the current method in a superclass. See methods

-yield Starts execution of the block sent to the current method. See methods

Methods Methods implement the functionality of your program. Here is a simple method

definition:

def one_plus_one 1 + 1 end

A method definition consists of the def keyword, a method name, the body of the

method, return value and the end keyword. When called the method will execute the

body of the method. This method returns 2.

This section only covers defining methods. See also the syntax documentation on

calling methods.

Method Names

Page 68: Ruby Keywords

Method names may be one of the operators or must start a letter or a character with the eight bit set. It may contain letters, numbers, an _ (underscore or low line) or a

character with the eight bit set. The convention is to use underscores to separate

words in a multiword method name:

def method_name puts "use underscores to separate words" end

Ruby programs must be written in a US-ASCII-compatible character set such as

UTF-8, ISO-8859-1 etc. In such character sets if the eight bit is set it indicates an

extended character. Ruby allows method names and other identifiers to contain such

characters. Ruby programs cannot contain some characters like ASCII NUL

(<code>x00<code>).

The following are the examples of valid ruby methods:

def hello "hello" end def こんにちは puts "means hello in Japanese" end

Typically method names are US-ASCII compatible since the keys to type them exist

on all keyboards.

Method names may end with a ! (bang or exclamation mark), a ? (question mark)

or = equals sign.

The bang methods (! at the end of method name) are called and executed just like

any other method. However, by convention, a method with an exclamation point or

bang is considered dangerous. In ruby core library the dangerous method implies that when a method ends with a bang (!), it indicates that unlike its non-bang

equivalent, permanently modifies its receiver. Almost always, ruby core library will have a non-bang counterpart (method name which does NOT end with !) of every

bang method (method name which does end with !) that does not modify the

receiver. This convention is typically true for ruby core library but may or may not

hold true for other ruby libraries.

Methods that end with a question mark by convention return boolean, but they may not always return just true or false. Often, they will return an object to indicate a true

value (or “truthy” value).

Methods that end with an equals sign indicate an assignment method. For

assignment methods, the return value is ignored and the arguments are returned

instead.

Page 69: Ruby Keywords

These are method names for the various ruby operators. Each of these operators

accept only one argument. Following the operator is the typical use or name of the

operator. Creating an alternate meaning for the operator may lead to confusion as

the user expects plus to add things, minus to subtract things, etc. Additionally, you

cannot alter the precedence of the operators.

+

add

-

subtract

*

multiply

**

power

/

divide

%

modulus division, String#% &

AND

^

XOR (exclusive OR)

>>

right-shift

<<

left-shift, append

==

equal

!=

not equal

===

case equality. See Object#=== =~

pattern match. (Not just for regular expressions)

!~

does not match

<=>

comparison aka spaceship operator. See Comparable <

less-than

<=

less-than or equal

>

Page 70: Ruby Keywords

greater-than

>=

greater-than or equal

To define unary methods minus, plus, tilde and not (!) follow the operator with

an @ as in +@ or !@:

class C def -@ puts "you inverted this object" end end obj = C.new -obj # prints "you inverted this object"

Unary methods accept zero arguments.

Additionally, methods for element reference and assignment may be defined: [] and []= respectively. Both can take one or more arguments, and element

reference can take none.

class C def [](a, b) puts a + b end def []=(a, b, c) puts a * b + c end end obj = C.new obj[2, 3] # prints "5" obj[2, 3] = 4 # prints "10"

Return Values

By default, a method returns the last expression that was evaluated in the body of the

method. In the example above, the last (and only) expression evaluated was the simple sum 1 + 1. The return keyword can be used to make it explicit that a method

returns a value.

def one_plus_one return 1 + 1 end

It can also be used to make a method return before the last expression is evaluated.

Page 71: Ruby Keywords

def two_plus_two return 2 + 2 1 + 1 # this expression is never evaluated end

Note that for assignment methods the return value will always be ignored. Instead,

the argument will be returned:

def a=(value) return 1 + value end p(a = 5) # prints 5

Scope

The standard syntax to define a method:

def my_method # ... end

adds the method to a class. You can define an instance method on a specific class with the class keyword:

class C def my_method # ... end end

A method may be defined on another object. You may define a “class method” (a

method that is defined on the class, not an instance of the class) like this:

class C def self.my_method # ... end end

Page 72: Ruby Keywords

However, this is simply a special case of a greater syntactical power in Ruby, the

ability to add methods to any object. Classes are objects, so adding class methods is

simply adding methods to the Class object.

The syntax for adding a method to an object is as follows:

greeting = "Hello" def greeting.broaden self + ", world!" end greeting.broaden # returns "Hello, world!"

self is a keyword referring to the current object under consideration by the compiler,

which might make the use of self in defining a class method above a little clearer.

Indeed, the example of adding a hello method to the class String can be rewritten

thus:

def String.hello "Hello, world!" end

A method defined like this is called a “singleton method”. broaden will only exist on

the string instance greeting. Other strings will not have broaden.

Overriding

When Ruby encounters the def keyword, it doesn't consider it an error if the method

already exists: it simply redefines it. This is called overriding. Rather like extending

core classes, this is a potentially dangerous ability, and should be used sparingly

because it can cause unexpected results. For example, consider this irb session:

>> "43".to_i

=> 43

>> class String

>> def to_i

>> 42

>> end

>> end

Page 73: Ruby Keywords

=> nil

>> "43".to_i

=> 42

This will effectively sabotage any code which makes use of the method String#to_i to parse numbers from strings.

Arguments A method may accept arguments. The argument list follows the method name:

def add_one(value) value + 1 end

When called, the user of the add_one method must provide an argument. The

argument is a local variable in the method body. The method will then add one to this argument and return the value. If given 1 this method will return 2.

The parentheses around the arguments are optional:

def add_one value value + 1 end

Multiple arguments are separated by a comma:

def add_values(a, b) a + b end

When called, the arguments must be provided in the exact order. In other words, the

arguments are positional.

Page 74: Ruby Keywords

Default Values

Arguments may have default values:

def add_values(a, b = 1) a + b end

The default value does not need to appear first, but arguments with defaults must be

grouped together. This is ok:

def add_values(a = 1, b = 2, c) a + b + c end

This will raise a SyntaxError:

def add_values(a = 1, b, c = 1)

a + b + c

end

Array Decomposition

You can decompose (unpack or extract values from) an Array using extra

parentheses in the arguments:

def my_method((a, b)) p a: a, b: b end my_method([1, 2])

This prints:

{:a=>1, :b=>2}

If the argument has extra elements in the Array they will be ignored:

def my_method((a, b)) p a: a, b: b end my_method([1, 2, 3])

This has the same output as above.

Page 75: Ruby Keywords

You can use a * to collect the remaining arguments. This splits an Array into a first

element and the rest:

def my_method((a, *b)) p a: a, b: b end my_method([1, 2, 3])

This prints:

{:a=>1, :b=>[2, 3]}

The argument will be decomposed if it responds to to_ary. You should only define

to_ary if you can use your object in place of an Array.

Use of the inner parentheses only uses one of the sent arguments. If the argument is

not an Array it will be assigned to the first argument in the decomposition and the remaining arguments in the decomposition will be nil:

def my_method(a, (b, c), d) p a: a, b: b, c: c, d: d end my_method(1, 2, 3)

This prints:

{:a=>1, :b=>2, :c=>nil, :d=>3}

You can nest decomposition arbitrarily:

def my_method(((a, b), c)) # ... end

Array/Hash Argument

Prefixing an argument with * causes any remaining arguments to be converted to an

Array:

def gather_arguments(*arguments) p arguments end gather_arguments 1, 2, 3 # prints [1, 2, 3]

The array argument must be the last positional argument, it must appear before any

keyword arguments.

Page 76: Ruby Keywords

The array argument will capture a Hash as the last entry if a hash was sent by the

caller after all positional arguments.

gather_arguments 1, a: 2 # prints [1, {:a=>2}]

However, this only occurs if the method does not declare any keyword arguments.

def gather_arguments_keyword(*positional, keyword: nil) p positional: positional, keyword: keyword end gather_arguments_keyword 1, 2, three: 3 #=> raises: unknown keyword: three (ArgumentError)

Also, note that a bare * can be used to ignore arguments:

def ignore_arguments(*) end

Keyword Arguments

Keyword arguments are similar to positional arguments with default values:

def add_values(first: 1, second: 2) first + second end

Arbitrary keyword arguments will be accepted with **:

def gather_arguments(first: nil, **rest) p first, rest end gather_arguments first: 1, second: 2, third: 3 # prints 1 then {:second=>2, :third=>3}

When calling a method with keyword arguments the arguments may appear in any

order. If an unknown keyword argument is sent by the caller an ArgumentError is

raised.

When mixing keyword arguments and positional arguments, all positional arguments

must appear before any keyword arguments.

Block Argument

Page 77: Ruby Keywords

The block argument is indicated by & and must come last:

def my_method(&my_block) my_block.call(self) end

Most frequently the block argument is used to pass a block to another method:

def each_item(&block) @items.each(&block) end

If you are only going to call the block and will not otherwise manipulate it or send it to another method using yield without an explicit block parameter is preferred. This

method is equivalent to the first method in this section:

def my_method yield self end

There is also a performance benefit to using yield over a calling a block parameter.

When a block argument is assigned to a variable a Proc object is created which holds

the block. When using yield this Proc object is not created.

If you only need to use the block sometimes you can use Proc.new to create a proc

from the block that was passed to your method. See Proc.new for further details.

Exception Handling Methods have an implied exception handling block so you do not need to use begin or end to handle exceptions. This:

def my_method begin # code that may raise an exception rescue # handle exception end end

May be written as:

def my_method # code that may raise an exception rescue # handle exception end

If you wish to rescue an exception for only part of your method, use begin and end.

For more details see the page on exception handling.

Page 78: Ruby Keywords

class Exception Descendants of class Exception are used to communicate

between Kernel#raise and rescue statements in begin ... end blocks. Exception objects

carry information about the exception – its type (the exception's class name), an optional

descriptive string, and optional traceback information. Exception subclasses may add

additional information like NameError#name.

Programs may make subclasses of Exception, typically of StandardError or RuntimeError, to

provide custom classes and add additional information. See the subclass list below for

defaults for raise and rescue.

When an exception has been raised but not yet handled

(in rescue, ensure, at_exit and END blocks) the global variable $! will contain the current

exception and $@ contains the current exception's backtrace.

It is recommended that a library should have one subclass

of StandardError or RuntimeError and have specific exception types inherit from it. This

allows the user to rescue a generic exception type to catch all exceptions the library may raise

even if future versions of the library add new exception subclasses.

For example:

class MyLibrary class Error < RuntimeError end class WidgetError < Error end class FrobError < Error end end

To handle both WidgetError and FrobError the library user can rescue MyLibrary::Error.

The built-in subclasses of Exception are:

NoMemoryError

ScriptError

o LoadError

o NotImplementedError

o SyntaxError

SecurityError

SignalException

o Interrupt

StandardError – default for rescue

o ArgumentError

UncaughtThrowError

o EncodingError

Page 79: Ruby Keywords

o FiberError

o IOError

EOFError

o IndexError

KeyError

StopIteration

o LocalJumpError

o NameError

NoMethodError

o RangeError

FloatDomainError

o RegexpError

o RuntimeError – default for raise

o SystemCallError

Errno::*

o ThreadError

o TypeError

o ZeroDivisionError

SystemExit

SystemStackError

fatal – impossible to rescue

Exception serialization/deserialization

Public Class Methods

exception(string) → an_excep on or exc

With no argument, or if the argument is the same as the receiver, return the receiver.

Otherwise, create a new exception object of the same class as the receiver, but with a message

equal to string.to_str. json_create(object)

Deserializes JSON string by constructing new Exception object with message m and

backtrace b serialized with to_json new(msg = nil) → excep on

Construct a new Exception object, optionally passing in a message.

Public Instance Methods

exc == obj → true or false

Page 80: Ruby Keywords

Equality—If obj is not an Exception, returns false. Otherwise,

returns true if exc and obj share same class, messages, and backtrace. as_json(*)

Returns a hash, that will be turned into a JSON object and represent this object. backtrace → array

Returns any backtrace associated with the exception. The backtrace is an array of strings, each

containing either “filename:lineNo: in `method''' or “filename:lineNo.''

def a raise "boom" end def b a() end begin b() rescue => detail print detail.backtrace.join("\n") end

produces:

prog.rb:2:in `a'

prog.rb:6:in `b'

prog.rb:10

backtrace_locations → array

Returns any backtrace associated with the exception. This method is similar to #backtrace, but

the backtrace is an array of

Thread::Backtrace::Location.

Now, this method is not affected by #set_backtrace. cause → an_excep on or nil

Returns the previous exception ($!) at the time this exception was raised. This is useful for

wrapping exceptions and retaining the original exception information.

exception(string) → an_excep on or exc

Page 81: Ruby Keywords

With no argument, or if the argument is the same as the receiver, return the receiver.

Otherwise, create a new exception object of the same class as the receiver, but with a message

equal to string.to_str. inspect → string

Return this exception's class name and message

message → string

Returns the result of invoking exception.to_s. Normally this returns the exception's

message or name. By supplying a to_str method, exceptions are agreeing to be used where

Strings are expected. set_backtrace(backtrace) → array

Sets the backtrace information associated with exc. The backtrace must be an array of String

objects or a single String in the format described in #backtrace. to_json(*args)

Stores class name (Exception) with message m and backtrace array b as JSON string to_s → stringclick to toggle source

Returns exception's message (or the name of the exception if no message is set).

 

Page 82: Ruby Keywords

-class Creates or opens a class. See modules and classes syntax

 

Modules Modules serve two purposes in Ruby, namespacing and mix-in functionality.

A namespace can be used to organize code by package or functionality that

separates common names from interference by other packages. For example, the

IRB namespace provides functionality for irb that prevents a collision for the common

name “Context”.

Mix-in functionality allows sharing common methods across multiple classes or

modules. Ruby comes with the Enumerable mix-in module which provides many enumeration methods based on the each method andComparable allows comparison

of objects based on the <=> comparison method.

Note that there are many similarities between modules and classes. Besides the

ability to mix-in a module, the description of modules below also applies to classes.

Module Definition A module is created using the module keyword:

module MyModule # ... end

A module may be reopened any number of times to add, change or remove

functionality:

module MyModule def my_method end end module MyModule alias my_alias my_method end module MyModule remove_method :my_method end

Reopening classes is a very powerful feature of Ruby, but it is best to only reopen

classes you own. Reopening classes you do not own may lead to naming conflicts or

difficult to diagnose bugs.

Page 83: Ruby Keywords

Nesting

Modules may be nested:

module Outer module Inner end end

Many packages create a single outermost module (or class) to provide a namespace

for their functionality.

You may also define inner modules using :: provided the outer modules (or classes)

are already defined:

module Outer::Inner::GrandChild end

Note that this will raise a NameError if Outer and Outer::Inner are not already

defined.

This style has the benefit of allowing the author to reduce the amount of indentation.

Instead of 3 levels of indentation only one is necessary. However, the scope of

constant lookup is different for creating a namespace using this syntax instead of the

more verbose syntax.

Scope self self refers to the object that defines the current scope. self will change when

entering a different method or when defining a new module.

Constants

Accessible constants are different depending on the module nesting (which syntax was used to define the module). In the following example the constant A::Z is

accessible from B as A is part of the nesting:

module A Z = 1 module B p Module.nesting #=> [A::B, A] p Z #=> 1 end end

Page 84: Ruby Keywords

However, if you use :: to define A::B without nesting it inside A,

a NameError exception will be raised because the nesting does not include A:

module A Z = 1 end module A::B p Module.nesting #=> [A::B] p Z #=> raises NameError end

If a constant is defined at the top-level you may preceded it with :: to reference it:

Z = 0 module A Z = 1 module B p ::Z #=> 0 end end

Methods

For method definition documentation see the syntax documentation for methods.

Class methods may be called directly. (This is slightly confusing, but a method on a

module is often called a “class method” instead of a “module method”. See

also Module#module_function which can convert an instance method into a class

method.)

When a class method references a constant, it uses the same rules as referencing it

outside the method as the scope is the same.

Instance methods defined in a module are only callable when included. These

methods have access to the constants defined when they were included through the

ancestors list:

module A Z = 1 def z Z end end include A p self.class.ancestors #=> [Object, A, Kernel, BasicObject] p z #=> 1

Page 85: Ruby Keywords

Visibility

Ruby has three types of visibility. The default is public. A public method may be

called from any other object. The second visibility is protected. When calling a protected method the sender must

be a subclass of the receiver or the receiver must be a subclass of the sender.

Otherwise a NoMethodError will be raised. Protected visibility is most frequently used to define == and other comparison

methods where the author does not wish to expose an object's state to any caller and

would like to restrict it only to inherited classes.

Here is an example:

class A def n(other) other.m end end class B < A def m 1 end protected :m end class C < B end a = A.new b = B.new c = C.new c.n b #=> 1 -- C is a subclass of B b.n b #=> 1 -- m called on defining class a.n b # raises NoMethodError A is not a subclass of B

The third visibility is private. A private method may not be called with a receiver, not

even self. If a private method is called with a receiver a NoMethodError will be

raised. alias and undef You may also alias or undefine methods, but these operations are not restricted to

modules or classes. See the miscellaneous syntax section for documentation.

Page 86: Ruby Keywords

Classes Every class is also a module, but unlike modules a class may not be mixed-in to

another module (or class). Like a module, a class can be used as a namespace. A

class also inherits methods and constants from its superclass.

Defining a class Use the class keyword to create a class:

class MyClass # ... end

If you do not supply a superclass your new class will inherit from Object. You may inherit from a different class using < followed by a class name:

class MySubclass < MyClass # ... end

There is a special class BasicObject which is designed as a blank class and includes

a minimum of built-in methods. You can use BasicObject to create an independent

inheritance structure. See the BasicObjectdocumentation for further details.

Inheritance Any method defined on a class is callable from its subclass:

class A Z = 1 def z Z end end class B < A end p B.new.z #=> 1

The same is true for constants:

class A Z = 1 end class B < A def z Z end

Page 87: Ruby Keywords

end p B.new.z #=> 1

You can override the functionality of a superclass method by redefining the method:

class A def m 1 end end class B < A def m 2 end end p B.new.m #=> 2

If you wish to invoke the superclass functionality from a method use super:

class A def m 1 end end class B < A def m 2 + super end end p B.new.m #=> 3

When used without any arguments super uses the arguments given to the subclass

method. To send no arguments to the superclass method use super(). To send

specific arguments to the superclass method provide them manually like super(2).

super may be called as many times as you like in the subclass method.

Singleton Classes The singleton class (also known as the metaclass or eigenclass) of an object is a

class that holds methods for only that instance. You can access the singleton class of an object using class << object like this:

class C end class << C # self is the singleton class here end

Page 88: Ruby Keywords

Most frequently you'll see the singleton class accessed like this:

class C class << self # ... end end

This allows definition of methods and attributes on a class (or module) without needing to write def self.my_method.

Since you can open the singleton class of any object this means that this code block:

o = Object.new def o.my_method 1 + 1 end

is equivalent to this code block:

o = Object.new class << o def my_method 1 + 1 end end

Both objects will have a my_method that returns 2.

class Module A Module is a collection of methods and constants. The methods in a module may be instance

methods or module methods. Instance methods appear as methods in a class when the module

is included, module methods do not. Conversely, module methods may be called without

creating an encapsulating object, while instance methods may not.

(See Module#module_function.)

In the descriptions that follow, the parameter sym refers to a symbol, which is either a quoted

string or a Symbol (such as :name).

module Mod include Math CONST = 1 def meth # ... end end Mod.class #=> Module Mod.constants #=> [:CONST, :PI, :E]

Page 89: Ruby Keywords

Mod.instance_methods #=> [:meth]

Public Class Methods

constants → array constants(inherited) → array In the first form, returns an array of the names of all constants accessible from the point of

call. This list includes the names of all modules and classes defined in the global scope.

Module.constants.first(4) # => [:ARGF, :ARGV, :ArgumentError, :Array] Module.constants.include?(:SEEK_SET) # => false class IO Module.constants.include?(:SEEK_SET) # => true end

The second form calls the instance method constants.

nesting → array Returns the list of Modules nested at the point of call.

module M1 module M2 $a = Module.nesting end end $a #=> [M1::M2, M1] $a[0].name #=> "M1::M2"

new → mod new {|mod| block } → mod Creates a new anonymous module. If a block is given, it is passed the module object, and the

block is evaluated in the context of this module using module_eval.

fred = Module.new do def meth1 "hello" end def meth2 "bye" end end a = "my string" a.extend(fred) #=> "my string" a.meth1 #=> "hello" a.meth2 #=> "bye"

Assign the module to a constant (name starting uppercase) if you want to treat it like a regular

module.

Page 90: Ruby Keywords

Public Instance Methods

mod < other → true, false, or nil Returns true if mod is a subclass of other. Returns nil if there's no relationship between the

two. (Think of the relationship in terms of the class definition: “class A<B” implies “A<B”.)

mod <= other → true, false, or nil Returns true if mod is a subclass of other or is the same as other. Returns nil if there's no

relationship between the two. (Think of the relationship in terms of the class definition: “class

A<B” implies “A<B”.)

module <=> other_module → -1, 0, +1, or nil Comparison—Returns -1, 0, +1 or nil depending on whether module includes other_module,

they are the same, or if module is included by other_module.

Returns nil if module has no relationship with other_module, if other_module is not a

module, or if the two values are incomparable.

obj == other → true or false equal?(other) → true or false eql?(other) → true or false Equality — At the Object level, == returns true only if obj and other are the same object.

Typically, this method is overridden in descendant classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses as it is used to

determine object identity (that is, a.equal?(b) if and only if a is the same object as b):

obj = "a" other = obj.dup obj == other #=> true obj.equal? other #=> false obj.equal? obj #=> true

The eql? method returns true if obj and other refer to the same hash key. This is used

by Hash to test members for equality. For objects of class Object, eql? is synonymous

with ==. Subclasses normally continue this tradition by aliasing eql? to their

overridden == method, 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

mod === obj → true or false Case Equality—Returns true if obj is an instance of mod or and instance of one of mod's

descendants. Of limited use for modules, but can be used in case statements to classify

objects by class.

mod > other → true, false, or nil

Page 91: Ruby Keywords

Returns true if mod is an ancestor of other. Returns nil if there's no relationship between the

two. (Think of the relationship in terms of the class definition: “class A<B” implies “B>A”.)

mod >= other → true, false, or nil Returns true if mod is an ancestor of other, or the two modules are the same. Returns nil if

there's no relationship between the two. (Think of the relationship in terms of the class

definition: “class A<B” implies “B>A”.)

ancestors → array Returns a list of modules included/prepended in mod (including mod itself).

module Mod include Math include Comparable prepend Enumerable end Mod.ancestors #=> [Enumerable, Mod, Comparable, Math] Math.ancestors #=> [Math] Enumerable.ancestors #=> [Enumerable]

autoload(module, filename) → nil Registers filename to be loaded (using Kernel::require) the first time that module (which

may be a String or a symbol) is accessed in the namespace of mod.

module A end A.autoload(:B, "b") A::B.doit # autoloads "b"

autoload?(name) → String or nil Returns filename to be loaded if name is registered as autoload in the namespace of mod.

module A end A.autoload(:B, "b") A.autoload?(:B) #=> "b"

class_eval(string [, filename [, lineno]]) → obj Evaluates the string or block in the context of mod, except that when a block is given,

constant/class variable lookup is not affected. This can be used to add methods to a

class. module_eval returns the result of evaluating its argument. The

optional filename and lineno parameters set the text for error messages.

class Thing end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123)

produces:

Page 92: Ruby Keywords

Hello there!

dummy:123:in `module_eval': undefined local variable

or method `code' for Thing:Class

class_exec(arg...) {|var...| block } → obj Evaluates the given block in the context of the class/module. The method defined in the block

will belong to the receiver. Any arguments passed to the method will be passed to the block.

This can be used if the block needs to access instance variables.

class Thing end Thing.class_exec{ def hello() "Hello there!" end } puts Thing.new.hello()

produces:

Hello there!

class_variable_defined?(symbol) → true or false class_variable_defined?(string) → true or false Returns true if the given class variable is defined in obj. String arguments are converted to

symbols.

class Fred @@foo = 99 end Fred.class_variable_defined?(:@@foo) #=> true Fred.class_variable_defined?(:@@bar) #=> false

class_variable_get(symbol) → obj class_variable_get(string) → obj Returns the value of the given class variable (or throws a NameError exception). The @@ part

of the variable name should be included for regular class variables. String arguments are

converted to symbols.

class Fred @@foo = 99 end Fred.class_variable_get(:@@foo) #=> 99

class_variable_set(symbol, obj) → obj class_variable_set(string, obj) → obj Sets the class variable named by symbol to the given object. If the class variable name is

passed as a string, that string is converted to a symbol.

Page 93: Ruby Keywords

class Fred @@foo = 99 def foo @@foo end end Fred.class_variable_set(:@@foo, 101) #=> 101 Fred.new.foo #=> 101

class_variables(inherit=true) → array Returns an array of the names of class variables in mod. This includes the names of class

variables in any included modules, unless the inherit parameter is set to false.

class One @@var1 = 1 end class Two < One @@var2 = 2 end One.class_variables #=> [:@@var1] Two.class_variables #=> [:@@var2, :@@var1] Two.class_variables(false) #=> [:@@var2]

const_defined?(sym, inherit=true) → true or false const_defined?(str, inherit=true) → true or false Says whether mod or its ancestors have a constant with the given name:

Float.const_defined?(:EPSILON) #=> true, found in Float itself Float.const_defined?("String") #=> true, found in Object (ancestor) BasicObject.const_defined?(:Hash) #=> false

If mod is a Module, additionally Object and its ancestors are checked:

Math.const_defined?(:String) #=> true, found in Object

In each of the checked classes or modules, if the constant is not present but there is an

autoload for it, true is returned directly without autoloading:

module Admin autoload :User, 'admin/user' end Admin.const_defined?(:User) #=> true

If the constant is not found the callback const_missing is not called and the method

returns false.

If inherit is false, the lookup only checks the constants in the receiver:

IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor) IO.const_defined?(:SYNC, false) #=> false, not found in IO itself

In this case, the same logic for autoloading applies.

Page 94: Ruby Keywords

If the argument is not a valid constant name a NameError is raised with the message “wrong

constant name name”:

Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar

const_get(sym, inherit=true) → obj const_get(str, inherit=true) → obj Checks for a constant with the given name in mod. If inherit is set, the lookup will also

search the ancestors (and Object if mod is a Module).

The value of the constant is returned if a definition is found, otherwise a NameError is raised.

Math.const_get(:PI) #=> 3.14159265358979

This method will recursively look up constant names if a namespaced class name is provided.

For example:

module Foo; class Bar; end end Object.const_get 'Foo::Bar'

The inherit flag is respected on each lookup. For example:

module Foo class Bar VAL = 10 end class Baz < Bar; end end Object.const_get 'Foo::Baz::VAL' # => 10 Object.const_get 'Foo::Baz::VAL', false # => NameError

If the argument is not a valid constant name a NameError will be raised with a warning

“wrong constant name”.

Object.const_get 'foobar' #=> NameError: wrong constant name foobar

const_missing(sym) → obj Invoked when a reference is made to an undefined constant in mod. It is passed a symbol for

the undefined constant, and returns a value to be used for that constant. The following code is

an example of the same:

def Foo.const_missing(name) name # return the constant name as Symbol end Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned

In the next example when a reference is made to an undefined constant, it attempts to load a

file whose name is the lowercase version of the constant (thus class Fred is assumed to be in

Page 95: Ruby Keywords

file fred.rb). If found, it returns the loaded class. It therefore implements an autoload feature

similar to Kernel#autoload and #autoload.

def Object.const_missing(name) @looked_for ||= {} str_name = name.to_s raise "Class not found: #{name}" if @looked_for[str_name] @looked_for[str_name] = 1 file = str_name.downcase require file klass = const_get(name) return klass if klass raise "Class not found: #{name}" end

const_set(sym, obj) → obj const_set(str, obj) → obj Sets the named constant to the given object, returning that object. Creates a new constant if no

constant with the given name previously existed.

Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714 Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968

If sym or str is not a valid constant name a NameError will be raised with a warning “wrong

constant name”.

Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar

constants(inherit=true) → array Returns an array of the names of the constants accessible in mod. This includes the names of

constants in any included modules (example at start of section), unless the inherit parameter is

set to false.

The implementation makes no guarantees about the order in which the constants are yielded.

IO.constants.include?(:SYNC) #=> true IO.constants(false).include?(:SYNC) #=> false

Also see Module::const_defined?.

deprecate_constant(*args)

freeze → mod Prevents further modifications to mod.

This method returns self.

include(module, ...) → self Invokes Module.append_features on each parameter in reverse order.

include?(module) → true or false Returns true if module is included in mod or one of mod's ancestors.

Page 96: Ruby Keywords

module A end class B include A end class C < B end B.include?(A) #=> true C.include?(A) #=> true A.include?(A) #=> false

included_modules → array Returns the list of modules included in mod.

module Mixin end module Outer include Mixin end Mixin.included_modules #=> [] Outer.included_modules #=> [Mixin]

inspect() Alias for: to_s

instance_method(symbol) → unbound_method Returns an UnboundMethod representing the given instance method in mod.

class Interpreter def do_a() print "there, "; end def do_d() print "Hello "; end def do_e() print "!\n"; end def do_v() print "Dave"; end Dispatcher = { "a" => instance_method(:do_a), "d" => instance_method(:do_d), "e" => instance_method(:do_e), "v" => instance_method(:do_v) } def interpret(string) string.each_char {|b| Dispatcher[b].bind(self).call } end end interpreter = Interpreter.new interpreter.interpret('dave')

produces:

Hello there, Dave!

instance_methods(include_super=true) → array Returns an array containing the names of the public and protected instance methods in the

receiver. For a module, these are the public and protected methods; for a class, they are the

Page 97: Ruby Keywords

instance (not singleton) methods. If the optional parameter is false, the methods of any

ancestors are not included.

module A def method1() end end class B include A def method2() end end class C < B def method3() end end A.instance_methods(false) #=> [:method1] B.instance_methods(false) #=> [:method2] B.instance_methods(true).include?(:method1) #=> true C.instance_methods(false) #=> [:method3] C.instance_methods.include?(:method2) #=> true

method_defined?(symbol) → true or false method_defined?(string) → true or false Returns true if the named method is defined by mod (or its included modules and, if mod is a

class, its ancestors). Public and protected methods are matched. String arguments are

converted to symbols.

module A def method1() end def protected_method1() end protected :protected_method1 end class B def method2() end def private_method2() end private :private_method2 end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.method_defined? "method1" #=> true C.method_defined? "method2" #=> true C.method_defined? "method3" #=> true C.method_defined? "protected_method1" #=> true C.method_defined? "method4" #=> false C.method_defined? "private_method2" #=> false

module_eval {|| block } → obj Evaluates the string or block in the context of mod, except that when a block is given,

constant/class variable lookup is not affected. This can be used to add methods to a

class. module_eval returns the result of evaluating its argument. The

optional filename and lineno parameters set the text for error messages.

class Thing

Page 98: Ruby Keywords

end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123)

produces:

Hello there!

dummy:123:in `module_eval': undefined local variable

or method `code' for Thing:Class

module_exec(arg...) {|var...| block } → obj Evaluates the given block in the context of the class/module. The method defined in the block

will belong to the receiver. Any arguments passed to the method will be passed to the block.

This can be used if the block needs to access instance variables.

class Thing end Thing.class_exec{ def hello() "Hello there!" end } puts Thing.new.hello()

produces:

Hello there!

name → string Returns the name of the module mod. Returns nil for anonymous modules.

prepend(module, ...) → self Invokes Module.prepend_features on each parameter in reverse order.

private_class_method(symbol, ...) → mod private_class_method(string, ...) → mod Makes existing class methods private. Often used to hide the default constructor new.

String arguments are converted to symbols.

class SimpleSingleton # Not thread safe private_class_method :new def SimpleSingleton.create(*args, &block) @me = new(*args, &block) if ! @me @me end end

private_constant(symbol, ...) → mod

Page 99: Ruby Keywords

Makes a list of existing constants private.

private_instance_methods(include_super=true) → array Returns a list of the private instance methods defined in mod. If the optional parameter

is false, the methods of any ancestors are not included.

module Mod def method1() end private :method1 def method2() end end Mod.instance_methods #=> [:method2] Mod.private_instance_methods #=> [:method1]

private_method_defined?(symbol) → true or false private_method_defined?(string) → true or false Returns true if the named private method is defined by _ mod_ (or its included modules and,

if mod is a class, its ancestors). String arguments are converted to symbols.

module A def method1() end end class B private def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.private_method_defined? "method1" #=> false C.private_method_defined? "method2" #=> true C.method_defined? "method2" #=> false

protected_instance_methods(include_super=true) → array Returns a list of the protected instance methods defined in mod. If the optional parameter

is false, the methods of any ancestors are not included.

protected_method_defined?(symbol) → true or false protected_method_defined?(string) → true or false Returns true if the named protected method is defined by mod (or its included modules and,

if mod is a class, its ancestors). String arguments are converted to symbols.

module A def method1() end end class B protected def method2() end end class C < B include A def method3() end

Page 100: Ruby Keywords

end A.method_defined? :method1 #=> true C.protected_method_defined? "method1" #=> false C.protected_method_defined? "method2" #=> true C.method_defined? "method2" #=> true

psych_yaml_as(url) Also aliased as: yaml_as

public_class_method(symbol, ...) → mod public_class_method(string, ...) → mod Makes a list of existing class methods public.

String arguments are converted to symbols.

public_constant(symbol, ...) → mod Makes a list of existing constants public.

public_instance_method(symbol) → unbound_method Similar to instance_method, searches public method only.

public_instance_methods(include_super=true) → array Returns a list of the public instance methods defined in mod. If the optional parameter

is false, the methods of any ancestors are not included.

public_method_defined?(symbol) → true or false public_method_defined?(string) → true or false Returns true if the named public method is defined by mod (or its included modules and,

if mod is a class, its ancestors). String arguments are converted to symbols.

module A def method1() end end class B protected def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.public_method_defined? "method1" #=> true C.public_method_defined? "method2" #=> false C.method_defined? "method2" #=> true

remove_class_variable(sym) → obj Removes the definition of the sym, returning that constant's value.

class Dummy @@var = 99 puts @@var

Page 101: Ruby Keywords

remove_class_variable(:@@var) p(defined? @@var) end

produces:

99 nil

singleton_class? → true or false Returns true if mod is a singleton class or false if it is an ordinary class or module.

class C end C.singleton_class? #=> false C.singleton_class.singleton_class? #=> true

to_s → string Returns a string representing this module or class. For basic classes and modules, this is the

name. For singletons, we show information on the thing we're attached to as well.

Also aliased as: inspect

yaml_as(url) Alias for: psych_yaml_as

Private Instance Methods

alias_method(new_name, old_name) → self Makes new_name a new copy of the method old_name. This can be used to retain access to

methods that are overridden.

module Mod alias_method :orig_exit, :exit def exit(code=0) puts "Exiting with code #{code}" orig_exit(code) end end include Mod exit(99)

produces:

Exiting with code 99

append_features(mod) → mod When this module is included in another, Ruby calls append_features in this module,

passing it the receiving module in mod. Ruby's default implementation is to add the constants,

Page 102: Ruby Keywords

methods, and module variables of this module to mod if this module has not already been

added to mod or one of its ancestors. See also Module#include.

attr(*args)

attr_accessor(symbol, ...) → nil attr_accessor(string, ...) → nil Defines a named attribute for this module, where the name is symbol.id2name, creating an

instance variable (@name) and a corresponding access method to read it. Also creates a method

called name= to set the attribute. String arguments are converted to symbols.

module Mod attr_accessor(:one, :two) end Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]

attr_reader(symbol, ...) → nil attr(symbol, ...) → nil attr_reader(string, ...) → nil attr(string, ...) → nil Creates instance variables and corresponding methods that return the value of each instance

variable. Equivalent to calling “attr:name'' on each name in turn. String arguments are

converted to symbols.

attr_writer(symbol, ...) → nil attr_writer(string, ...) → nil Creates an accessor method to allow assignment to the attribute symbol.id2name. String

arguments are converted to symbols.

define_method(symbol, method) → symbol define_method(symbol) { block } → symbol Defines an instance method in the receiver. The method parameter can be a Proc, a Method or

an UnboundMethod object. If a block is specified, it is used as the method body. This block is

evaluated using instance_eval, a point that is tricky to demonstrate

because define_method is private. (This is why we resort to the send hack in this example.)

class A def fred puts "In Fred" end def create_method(name, &block) self.class.send(:define_method, name, &block) end define_method(:wilma) { puts "Charge it!" } end class B < A define_method(:barney, instance_method(:fred)) end a = B.new a.barney a.wilma a.create_method(:betty) { p self }

Page 103: Ruby Keywords

a.betty

produces:

In Fred Charge it! #<B:0x401b39e8>

extend_object(obj) → obj 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 puts "Can't add Picky to a String" else puts "Picky added to #{o.class}" super end end end (s = Array.new).extend Picky # Call Object.extend (s = "quick brown fox").extend Picky

produces:

Picky added to Array

Can't add Picky to a String

extended(othermod) The equivalent of included, but for extended modules.

module A def self.extended(mod) puts "#{self} extended in #{mod}" end end module Enumerable extend A end # => prints "A extended in Enumerable"

included(othermod) Callback invoked whenever the receiver is included in another module or class. This should

be used in preference to Module.append_features if your code wants to perform some

action when a module is included in another.

module A def A.included(mod) puts "#{self} included in #{mod}"

Page 104: Ruby Keywords

end end module Enumerable include A end # => prints "A included in Enumerable"

method_added(method_name) Invoked as a callback whenever an instance method is added to the receiver.

module Chatty def self.method_added(method_name) puts "Adding #{method_name.inspect}" end def self.some_class_method() end def some_instance_method() end end

produces:

Adding :some_instance_method

method_removed(method_name) Invoked as a callback whenever an instance method is removed from the receiver.

module Chatty def self.method_removed(method_name) puts "Removing #{method_name.inspect}" end def self.some_class_method() end def some_instance_method() end class << self remove_method :some_class_method end remove_method :some_instance_method end

produces:

Removing :some_instance_method

method_undefined(p1) Not documented

module_function(symbol, ...) → self module_function(string, ...) → self Creates module functions for the named methods. These functions may be called with the

module as a receiver, and also become available as instance methods to classes that mix in the

module. Module functions are copies of the original, and so may be changed independently.

The instance-method versions are made private. If used with no arguments, subsequently

defined methods become module functions. String arguments are converted to symbols.

Page 105: Ruby Keywords

module Mod def one "This is one" end module_function :one end class Cls include Mod def call_one one end end Mod.one #=> "This is one" c = Cls.new c.call_one #=> "This is one" module Mod def one "This is the new one" end end Mod.one #=> "This is one" c.call_one #=> "This is the new one"

prepend_features(mod) → mod When this module is prepended in another, Ruby calls prepend_features in this module,

passing it the receiving module in mod. Ruby's default implementation is to overlay the

constants, methods, and module variables of this module to mod if this module has not already

been added to mod or one of its ancestors. See also Module#prepend.

prepended(othermod) The equivalent of included, but for prepended modules.

module A def self.prepended(mod) puts "#{self} prepended to #{mod}" end end module Enumerable prepend A end # => prints "A prepended to Enumerable"

private → self private(symbol, ...) → self private(string, ...) → self With no arguments, sets the default visibility for subsequently defined methods to private.

With arguments, sets the named methods to have private visibility. String arguments are

converted to symbols.

module Mod def a() end def b() end private def c() end private :a

Page 106: Ruby Keywords

end Mod.private_instance_methods #=> [:a, :c]

protected → self protected(symbol, ...) → self protected(string, ...) → self With no arguments, sets the default visibility for subsequently defined methods to protected.

With arguments, sets the named methods to have protected visibility. String arguments are

converted to symbols.

public → self public(symbol, ...) → self public(string, ...) → self With no arguments, sets the default visibility for subsequently defined methods to public.

With arguments, sets the named methods to have public visibility. String arguments are

converted to symbols.

refine(klass) { block } → module Refine klass in the receiver.

Returns an overlaid module.

remove_const(sym) → obj Removes the definition of the given constant, returning that constant's previous value. If that

constant referred to a module, this will not change that module's name and can lead to

confusion.

remove_method(symbol) → self remove_method(string) → self Removes the method identified by symbol from the current class. For an example,

see Module.undef_method. String arguments are converted to symbols.

undef_method(symbol) → self undef_method(string) → self Prevents the current class from responding to calls to the named method. Contrast this

with remove_method, which deletes the method from the particular class; Ruby will still

search superclasses and mixed-in modules for a possible receiver. String arguments are

converted to symbols.

class Parent def hello puts "In parent" end end class Child < Parent def hello puts "In child" end end c = Child.new

Page 107: Ruby Keywords

c.hello class Child remove_method :hello # remove from child, still in parent end c.hello class Child undef_method :hello # prevent any calls to 'hello' end c.hello

produces:

In child

In parent

prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError)

using(module) → self Import class refinements from module into the current class or module definition.

module Singleton The Singleton module implements the Singleton pattern.

Usage To use Singleton, include the module in your class.

class Klass include Singleton # ... end

This ensures that only one instance of Klass can be created.

a,b = Klass.instance, Klass.instance a == b # => true Klass.new # => NoMethodError - new is private ...

The instance is created at upon the first call of Klass.instance().

Page 108: Ruby Keywords

class OtherKlass include Singleton # ... end ObjectSpace.each_object(OtherKlass){} # => 0 OtherKlass.instance ObjectSpace.each_object(OtherKlass){} # => 1

This behavior is preserved under inheritance and cloning.

Implementation This above is achieved by:

Making Klass.new and Klass.allocate private.

Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that

the Singleton properties are kept when inherited and cloned.

Providing the Klass.instance() method that returns the same object each time it is

called.

Overriding Klass._load(str) to call Klass.instance().

Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent cloning or

duping.

Singleton and Marshal By default Singleton's #_dump(depth) returns the empty string. Marshalling by default will

strip state information, e.g. instance variables and taint state, from the instance. Classes

using Singleton can provide custom _load(str) and _dump(depth) methods to retain some of

the previous state of the instance.

require 'singleton' class Example include Singleton attr_accessor :keep, :strip def _dump(depth) # this strips the @strip information from the instance Marshal.dump(@keep, depth) end def self._load(str) instance.keep = Marshal.load(str) instance end end a = Example.instance

Page 109: Ruby Keywords

a.keep = "keep this" a.strip = "get rid of this" a.taint stored_state = Marshal.dump(a) a.keep = nil a.strip = nil b = Marshal.load(stored_state) p a == b # => true p a.keep # => "keep this" p a.strip # => nil

Public Class Methods

_load()

By default calls instance(). Override to retain singleton state.

Private Class Methods

append_features(mod)

Calls superclass method

included(klass)

Calls superclass method

Public Instance Methods

_dump(depth = -1)

By default, do not retain any state when marshalling.

clone()

Raises a TypeError to prevent cloning. dup()

Raises a TypeError to prevent duping.

 

module Marshal

Page 110: Ruby Keywords

The marshaling library converts collections of Ruby objects into a byte stream, allowing them

to be stored outside the currently active script. This data may subsequently be read and the

original objects reconstituted.

Marshaled data has major and minor version numbers stored along with the object

information. In normal use, marshaling can only load data written with the same major

version number and an equal or lower minor version number. If Ruby's “verbose'' flag is set

(normally using -d, -v, -w, or –verbose) the major and minor numbers must match

exactly. Marshal versioning is independent of Ruby's version numbers. You can extract the

version by reading the first two bytes of marshaled data.

str = Marshal.dump("thing") RUBY_VERSION #=> "1.9.0" str[0].ord #=> 4 str[1].ord #=> 8

Some objects cannot be dumped: if the objects to be dumped include bindings, procedure or

method objects, instances of class IO, or singleton objects, a TypeError will be raised.

If your class has special serialization needs (for example, if you want to serialize in some

specific format), or if it contains objects that would otherwise not be serializable, you can

implement your own serialization strategy.

There are two methods of doing this, your object can define either marshal_dump and

marshal_load or _dump and _load. marshal_dump will take precedence over _dump if both

are defined. marshal_dump may result in smaller Marshal strings.

Security considerations By design, ::load can deserialize almost any class loaded into the Ruby process. In many cases

this can lead to remote code execution if the Marshal data is loaded from an untrusted source.

As a result, ::load is not suitable as a general purpose serialization format and you should

never unmarshal user supplied input or other untrusted data.

If you need to deserialize untrusted data, use JSON or another serialization format that is only

able to load simple, 'primitive' types such as String, Array, Hash, etc. Never allow user input

to specify arbitrary types to deserialize into.

marshal_dump and marshal_load When dumping an object the method marshal_dump will be called. marshal_dump must

return a result containing the information necessary for marshal_load to reconstitute the

object. The result can be any object.

When loading an object dumped using marshal_dump the object is first allocated then

marshal_load is called with the result from marshal_dump. marshal_load must recreate the

object from the information in the result.

Page 111: Ruby Keywords

Example:

class MyObj def initialize name, version, data @name = name @version = version @data = data end def marshal_dump [@name, @version] end def marshal_load array @name, @version = array end end

_dump and _load Use _dump and _load when you need to allocate the object you're restoring yourself.

When dumping an object the instance method _dump is called with an Integer which indicates

the maximum depth of objects to dump (a value of -1 implies that you should disable depth

checking). _dump must return a String containing the information necessary to reconstitute

the object.

The class method _load should take a String and use it to return an object of the same class.

Example:

class MyObj def initialize name, version, data @name = name @version = version @data = data end def _dump level [@name, @version].join ':' end def self._load args new(*args.split(':')) end end

Since ::dump outputs a string you can have _dump return a Marshal string which is

Marshal.loaded in _load for complex objects.

Constants

MAJOR_VERSION

Page 112: Ruby Keywords

major version

MINOR_VERSION

minor version

Public Class Methods

dump( obj [, anIO] , limit=-1 ) → anIO Serializes obj and all descendant objects. If anIO is specified, the serialized data will be

written to it, otherwise the data will be returned as a String. If limit is specified, the traversal

of subobjects will be limited to that depth. If limit is negative, no checking of depth will be

performed.

class Klass def initialize(str) @str = str end def say_hello @str end end

(produces no output)

o = Klass.new("hello\n") data = Marshal.dump(o) obj = Marshal.load(data) obj.say_hello #=> "hello\n"

Marshal can't dump following objects:

anonymous Class/Module.

objects which are related to system (ex: Dir, File::Stat, IO, File, Socket and so on)

an instance

of MatchData, Data, Method, UnboundMethod, Proc, Thread, ThreadGroup, Continu

ation

objects which define singleton methods

load( source [, proc] ) → obj Returns the result of converting the serialized data in source into a Ruby object (possibly with

associated subordinate objects). source may be either an instance of IO or an object that

responds to to_str. If proc is specified, each object will be passed to the proc, as the object is

being deserialized.

Never pass untrusted data (including user supplied input) to this method. Please see the

overview for further details.

restore( source [, proc] ) → obj

Page 113: Ruby Keywords

Returns the result of converting the serialized data in source into a Ruby object (possibly with

associated subordinate objects). source may be either an instance of IO or an object that

responds to to_str. If proc is specified, each object will be passed to the proc, as the object is

being deserialized.

Never pass untrusted data (including user supplied input) to this method. Please see the

overview for further details.

 

Page 114: Ruby Keywords

-case Starts a case expression. See control expressions syntax

 

Control Expressions Ruby has a variety of ways to control execution. All the expressions described here

return a value.

For the tests in these control expressions, nil and false are false-values

and true and any other object are true-values. In this document “true” will mean

“true-value” and “false” will mean “false-value”.

if Expression The simplest if expression has two parts, a “test” expression and a “then”

expression. If the “test” expression evaluates to a true then the “then” expression is

evaluated.

Here is a simple if statement:

if true then puts "the test resulted in a true-value" end

This will print “the test resulted in a true-value”.

The then is optional:

if true puts "the test resulted in a true-value" end

This document will omit the optional then for all expressions as that is the most

common usage of if.

You may also add an else expression. If the test does not evaluate to true

the else expression will be executed:

if false puts "the test resulted in a true-value" else puts "the test resulted in a false-value" end

Page 115: Ruby Keywords

This will print “the test resulted in a false-value”.

You may add an arbitrary number of extra tests to an if expression using elsif.

An elsif executes when all tests above the elsif are false.

a = 1 if a == 0 puts "a is zero" elsif a == 1 puts "a is one" else puts "a is some other value" end

This will print “a is one” as 1 is not equal to 0. Since else is only executed when there

are no matching conditions. Once a condition matches, either the if condition or any elsif condition,

the if expression is complete and no further tests will be performed.

Like an if, an elsif condition may be followed by a then.

In this example only “a is one” is printed:

a = 1 if a == 0 puts "a is zero" elsif a == 1 puts "a is one" elsif a >= 1 puts "a is greater than or equal to one" else puts "a is some other value" end

The tests for if and elsif may have side-effects. The most common use of side-

effect is to cache a value into a local variable:

if a = object.some_value # do something to a end

The result value of an if expression is the last value executed in the expression.

Ternary if

You may also write a if-then-else expression using ? and :. This ternary if:

input_type = gets =~ /hello/i ? "greeting" : "other"

Page 116: Ruby Keywords

Is the same as this if expression:

input_type = if gets =~ /hello/i "greeting" else "other" end

While the ternary if is much shorter to write than the more verbose form, for

readability it is recommended that the ternary if is only used for simple conditionals.

Also, avoid using multiple ternary conditions in the same expression as this can be

confusing.

unless Expression The unless expression is the opposite of the if expression. If the value is false, the

“then” expression is executed:

unless true puts "the value is a false-value" end

This prints nothing as true is not a false-value.

You may use an optional then with unless just like if.

Note that the above unless expression is the same as:

if not true puts "the value is a false-value" end

Like an if expression you may use an else condition with unless:

unless true puts "the value is false" else puts "the value is true" end

This prints “the value is true” from the else condition.

You may not use elsif with an unless expression.

The result value of an unless expression is the last value executed in the expression.

Modifier if and unless if and unless can also be used to modify an expression. When used as a modifier

the left-hand side is the “then” expression and the right-hand side is the “test”

expression:

Page 117: Ruby Keywords

a = 0 a += 1 if a.zero? p a

This will print 1.

a = 0 a += 1 unless a.zero? p a

This will print 0.

While the modifier and standard versions have both a “test” expression and a “then”

expression, they are not exact transformations of each other due to parse order. Here

is an example that shows the difference:

p a if a = 0.zero?

This raises the NameError “undefined local variable or method `a'”. When ruby parses this expression it first encounters a as a method call in the “then”

expression, then later it sees the assignment to a in the “test” expression and

marks a as a local variable.

When running this line it first executes the “test” expression, a = 0.zero?.

Since the test is true it executes the “then” expression, p a. Since the a in the body

was recorded as a method which does not exist the NameError is raised. The same is true for unless.

case Expression The case expression can be used in two ways.

The most common way is to compare an object against multiple patterns. The

patterns are matched using the +===+ method which is aliased to +==+ on Object.

Other classes must override it to give meaningful behavior.

SeeModule#=== and Regexp#=== for examples. Here is an example of using case to compare a String against a pattern:

case "12345" when /^1/ puts "the string starts with one" else puts "I don't know what the string starts with" end

Page 118: Ruby Keywords

Here the string "12345" is compared with /^1/ by calling /^1/ === "12345" which

returns true. Like the if expression, the first when that matches is executed and all

other matches are ignored. If no matches are found, the else is executed.

The else and then are optional, this case expression gives the same result as the

one above:

case "12345" when /^1/ puts "the string starts with one" end

You may place multiple conditions on the same when:

case "2" when /^1/, "2" puts "the string starts with one or is '2'" end

Ruby will try each condition in turn, so first /^1/ === "2" returns false, then "2" ===

"2" returns true, so “the string starts with one or is '2'” is printed.

You may use then after the when condition. This is most frequently used to place the

body of the when on a single line.

case a

when 1, 2 then puts "a is one or two

when 3 then puts "a is three"

else puts "I don't know what a is"

end

The other way to use a case expression is like an if-elsif expression:

a = 2 case when a == 1, a == 2 puts "a is one or two" when a == 3 puts "a is three" else puts "I don't know what a is" end

Again, the then and else are optional.

The result value of a case expression is the last value executed in the expression.

Page 119: Ruby Keywords

while Loop The while loop executes while a condition is true:

a = 0 while a < 10 do p a a += 1 end p a

Prints the numbers 0 through 10. The condition a < 10 is checked before the loop is

entered, then the body executes, then the condition is checked again. When the

condition results in false the loop is terminated. The do keyword is optional. The following loop is equivalent to the loop above:

while a < 10 p a a += 1 end

The result of a while loop is nil unless break is used to supply a value.

until Loop The until loop executes while a condition is false:

a = 0 until a > 10 do p a a += 1 end p a

This prints the numbers 0 through 11. Like a while loop the condition a > 10 is

checked when entering the loop and each time the loop body executes. If the

condition is false the loop will continue to execute. Like a while loop, the do is optional.

Like a while loop, the result of an until loop is nil unless break is used.

for Loop The for loop consists of for followed by a variable to contain the iteration argument

followed by in and the value to iterate over using each. The do is optional:

Page 120: Ruby Keywords

for value in [1, 2, 3] do puts value end

Prints 1, 2 and 3.

Like while and until, the do is optional.

The for loop is similar to using each, but does not create a new variable scope.

The result value of a for loop is the value iterated over unless break is used.

The for loop is rarely used in modern ruby programs.

Modifier while and until Like if and unless, while and until can be used as modifiers:

a = 0 a += 1 while a < 10 p a # prints 10

until used as a modifier:

a = 0 a += 1 until a > 10 p a # prints 11

You can use begin and end to create a while loop that runs the body once before the

condition:

a = 0 begin a += 1 end while a < 10 p a # prints 10

If you don't use rescue or ensure, Ruby optimizes away any exception handling

overhead.

break Statement Use break to leave a block early. This will stop iterating over the items in values if

one of them is even:

values.each do |value| break if value.even?

Page 121: Ruby Keywords

# ... end

You can also terminate from a while loop using break:

a = 0 while true do p a a += 1 break if a < 10 end p a

This prints the numbers 0 and 1.

break accepts a value that supplies the result of the expression it is “breaking” out of:

result = [1, 2, 3].each do |value| break value * 2 if value.even? end p result # prints 4

next Statement Use next to skip the rest of the current iteration:

result = [1, 2, 3].map do |value| next if value.even? value * 2 end p result # prints [2, nil, 6]

next accepts an argument that can be used the result of the current block iteration:

result = [1, 2, 3].map do |value| next value if value.even? value * 2 end p result # prints [2, 2, 6]

Page 122: Ruby Keywords

redo Statement Use redo to redo the current iteration:

result = [] while result.length < 10 do result << result.length redo if result.last.even? result << result.length + 1 end p result

This prints [0, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]

In Ruby 1.8, you could also use retry where you used redo. This is no longer true,

now you will receive a SyntaxError when you use retry outside of a rescue block.

See Exceptions for proper usage of retry.

Flip-Flop

The flip-flop is a rarely seen conditional expression. It's primary use is for processing text from ruby one-line programs used with ruby -n or ruby -p.

The form of the flip-flop is an expression that indicates when the flip-flop turns on, .. (or ...), then an expression that indicates when the flip-flop will turn off. While

the flip-flop is on it will continue to evaluate to true, andfalse when off.

Here is an example:

selected = [] 0.upto 10 do |value| selected << value if value==2..value==8 end p selected # prints [2, 3, 4, 5, 6, 7, 8]

In the above example, the on condition is n==2. The flip-flop is initially off (false) for 0

and 1, but becomes on (true) for 2 and remains on through 8. After 8 it turns off and

remains off for 9 and 10. The flip-flop must be used inside a conditional such as if, while, unless, until etc.

including the modifier forms. When you use an inclusive range (..), the off condition is evaluated when the on

condition changes:

Page 123: Ruby Keywords

selected = [] 0.upto 5 do |value| selected << value if value==2..value==2 end p selected # prints [2]

Here, both sides of the flip-flop are evaluated so the flip-flop turns on and off only when value equals 2. Since the flip-flop turned on in the iteration it returns true.

When you use an exclusive range (...), the off condition is evaluated on the

following iteration:

selected = [] 0.upto 5 do |value| selected << value if value==2...value==2 end p selected # prints [2, 3, 4, 5]

Here, the flip-flop turns on when value equals 2, but doesn't turn off on the same

iteration. The off condition isn't evaluated until the following iteration and value will

never be two again  

Page 124: Ruby Keywords

-do Starts a block.

-else The unhandled condition in case, if and unless expressions. See control expressions

 

Control Expressions Ruby has a variety of ways to control execution. All the expressions described here

return a value.

For the tests in these control expressions, nil and false are false-values

and true and any other object are true-values. In this document “true” will mean

“true-value” and “false” will mean “false-value”.

if Expression The simplest if expression has two parts, a “test” expression and a “then”

expression. If the “test” expression evaluates to a true then the “then” expression is

evaluated.

Here is a simple if statement:

if true then puts "the test resulted in a true-value" end

This will print “the test resulted in a true-value”.

The then is optional:

if true puts "the test resulted in a true-value" end

This document will omit the optional then for all expressions as that is the most

common usage of if.

You may also add an else expression. If the test does not evaluate to true

the else expression will be executed:

if false puts "the test resulted in a true-value" else puts "the test resulted in a false-value"

Page 125: Ruby Keywords

end

This will print “the test resulted in a false-value”.

You may add an arbitrary number of extra tests to an if expression using elsif.

An elsif executes when all tests above the elsif are false.

a = 1 if a == 0 puts "a is zero" elsif a == 1 puts "a is one" else puts "a is some other value" end

This will print “a is one” as 1 is not equal to 0. Since else is only executed when there

are no matching conditions. Once a condition matches, either the if condition or any elsif condition,

the if expression is complete and no further tests will be performed.

Like an if, an elsif condition may be followed by a then.

In this example only “a is one” is printed:

a = 1 if a == 0 puts "a is zero" elsif a == 1 puts "a is one" elsif a >= 1 puts "a is greater than or equal to one" else puts "a is some other value" end

The tests for if and elsif may have side-effects. The most common use of side-

effect is to cache a value into a local variable:

if a = object.some_value # do something to a end

The result value of an if expression is the last value executed in the expression.

Ternary if You may also write a if-then-else expression using ? and :. This ternary if:

input_type = gets =~ /hello/i ? "greeting" : "other"

Is the same as this if expression:

Page 126: Ruby Keywords

input_type = if gets =~ /hello/i "greeting" else "other" end

While the ternary if is much shorter to write than the more verbose form, for

readability it is recommended that the ternary if is only used for simple conditionals.

Also, avoid using multiple ternary conditions in the same expression as this can be

confusing.

unless Expression The unless expression is the opposite of the if expression. If the value is false, the

“then” expression is executed:

unless true puts "the value is a false-value" end

This prints nothing as true is not a false-value.

You may use an optional then with unless just like if.

Note that the above unless expression is the same as:

if not true puts "the value is a false-value" end

Like an if expression you may use an else condition with unless:

unless true puts "the value is false" else puts "the value is true" end

This prints “the value is true” from the else condition.

You may not use elsif with an unless expression.

The result value of an unless expression is the last value executed in the expression.

Page 127: Ruby Keywords

Modifier if and unless

if and unless can also be used to modify an expression. When used as a modifier

the left-hand side is the “then” expression and the right-hand side is the “test”

expression:

a = 0 a += 1 if a.zero? p a

This will print 1.

a = 0 a += 1 unless a.zero? p a

This will print 0.

While the modifier and standard versions have both a “test” expression and a “then”

expression, they are not exact transformations of each other due to parse order. Here

is an example that shows the difference:

p a if a = 0.zero?

This raises the NameError “undefined local variable or method `a'”. When ruby parses this expression it first encounters a as a method call in the “then”

expression, then later it sees the assignment to a in the “test” expression and

marks a as a local variable.

When running this line it first executes the “test” expression, a = 0.zero?.

Since the test is true it executes the “then” expression, p a. Since the a in the body

was recorded as a method which does not exist the NameError is raised. The same is true for unless.

case Expression The case expression can be used in two ways.

The most common way is to compare an object against multiple patterns. The

patterns are matched using the +===+ method which is aliased to +==+ on Object.

Other classes must override it to give meaningful behavior.

SeeModule#=== and Regexp#=== for examples. Here is an example of using case to compare a String against a pattern:

Page 128: Ruby Keywords

case "12345" when /^1/ puts "the string starts with one" else puts "I don't know what the string starts with" end

Here the string "12345" is compared with /^1/ by calling /^1/ === "12345" which

returns true. Like the if expression, the first when that matches is executed and all

other matches are ignored. If no matches are found, the else is executed.

The else and then are optional, this case expression gives the same result as the

one above:

case "12345" when /^1/ puts "the string starts with one" end

You may place multiple conditions on the same when:

case "2" when /^1/, "2" puts "the string starts with one or is '2'" end

Ruby will try each condition in turn, so first /^1/ === "2" returns false, then "2" ===

"2" returns true, so “the string starts with one or is '2'” is printed.

You may use then after the when condition. This is most frequently used to place the

body of the when on a single line.

case a

when 1, 2 then puts "a is one or two

when 3 then puts "a is three"

else puts "I don't know what a is"

end

The other way to use a case expression is like an if-elsif expression:

a = 2 case when a == 1, a == 2 puts "a is one or two" when a == 3 puts "a is three" else

Page 129: Ruby Keywords

puts "I don't know what a is" end

Again, the then and else are optional.

The result value of a case expression is the last value executed in the expression.

while Loop The while loop executes while a condition is true:

a = 0 while a < 10 do p a a += 1 end p a

Prints the numbers 0 through 10. The condition a < 10 is checked before the loop is

entered, then the body executes, then the condition is checked again. When the

condition results in false the loop is terminated. The do keyword is optional. The following loop is equivalent to the loop above:

while a < 10 p a a += 1 end

The result of a while loop is nil unless break is used to supply a value.

until Loop The until loop executes while a condition is false:

a = 0 until a > 10 do p a a += 1 end p a

This prints the numbers 0 through 11. Like a while loop the condition a > 10 is

checked when entering the loop and each time the loop body executes. If the

condition is false the loop will continue to execute. Like a while loop, the do is optional.

Like a while loop, the result of an until loop is nil unless break is used.

Page 130: Ruby Keywords

for Loop The for loop consists of for followed by a variable to contain the iteration argument

followed by in and the value to iterate over using each. The do is optional:

for value in [1, 2, 3] do puts value end

Prints 1, 2 and 3.

Like while and until, the do is optional.

The for loop is similar to using each, but does not create a new variable scope.

The result value of a for loop is the value iterated over unless break is used.

The for loop is rarely used in modern ruby programs.

Modifier while and until Like if and unless, while and until can be used as modifiers:

a = 0 a += 1 while a < 10 p a # prints 10

until used as a modifier:

a = 0 a += 1 until a > 10 p a # prints 11

You can use begin and end to create a while loop that runs the body once before the

condition:

a = 0 begin a += 1 end while a < 10 p a # prints 10

If you don't use rescue or ensure, Ruby optimizes away any exception handling

overhead.

Page 131: Ruby Keywords

break Statement Use break to leave a block early. This will stop iterating over the items in values if

one of them is even:

values.each do |value| break if value.even? # ... end

You can also terminate from a while loop using break:

a = 0 while true do p a a += 1 break if a < 10 end p a

This prints the numbers 0 and 1.

break accepts a value that supplies the result of the expression it is “breaking” out of:

result = [1, 2, 3].each do |value| break value * 2 if value.even? end p result # prints 4

next Statement Use next to skip the rest of the current iteration:

result = [1, 2, 3].map do |value| next if value.even? value * 2 end p result # prints [2, nil, 6]

next accepts an argument that can be used the result of the current block iteration:

result = [1, 2, 3].map do |value| next value if value.even? value * 2 end

Page 132: Ruby Keywords

p result # prints [2, 2, 6]

redo Statement Use redo to redo the current iteration:

result = [] while result.length < 10 do result << result.length redo if result.last.even? result << result.length + 1 end p result

This prints [0, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]

In Ruby 1.8, you could also use retry where you used redo. This is no longer true,

now you will receive a SyntaxError when you use retry outside of a rescue block.

See Exceptions for proper usage of retry.

Flip-Flop The flip-flop is a rarely seen conditional expression. It's primary use is for processing text from ruby one-line programs used with ruby -n or ruby -p.

The form of the flip-flop is an expression that indicates when the flip-flop turns on, .. (or ...), then an expression that indicates when the flip-flop will turn off. While

the flip-flop is on it will continue to evaluate to true, andfalse when off.

Here is an example:

selected = [] 0.upto 10 do |value| selected << value if value==2..value==8 end p selected # prints [2, 3, 4, 5, 6, 7, 8]

In the above example, the on condition is n==2. The flip-flop is initially off (false) for 0

and 1, but becomes on (true) for 2 and remains on through 8. After 8 it turns off and

remains off for 9 and 10. The flip-flop must be used inside a conditional such as if, while, unless, until etc.

including the modifier forms. When you use an inclusive range (..), the off condition is evaluated when the on

condition changes:

Page 133: Ruby Keywords

selected = [] 0.upto 5 do |value| selected << value if value==2..value==2 end p selected # prints [2]

Here, both sides of the flip-flop are evaluated so the flip-flop turns on and off only when value equals 2. Since the flip-flop turned on in the iteration it returns true.

When you use an exclusive range (...), the off condition is evaluated on the

following iteration:

selected = [] 0.upto 5 do |value| selected << value if value==2...value==2 end p selected # prints [2, 3, 4, 5]

Here, the flip-flop turns on when value equals 2, but doesn't turn off on the same

iteration. The off condition isn't evaluated until the following iteration and value will

never be two again.  

Page 134: Ruby Keywords

-defined? Returns a string describing its argument. See miscellaneous syntax

Miscellaneous Syntax

Ending an Expression Ruby uses a newline as the end of an expression. When ending a line with an

operator, open parentheses, comma, etc. the expression will continue.

You can end an expression with a ; (semicolon). Semicolons are most frequently

used with ruby -e.

Indentation Ruby does not require any indentation. Typically, ruby programs are indented two

spaces.

If you run ruby with warnings enabled and have an indentation mis-match, you will

receive a warning.

alias The alias keyword is most frequently used to alias methods. When aliasing a

method, you can use either its name or a symbol:

alias new_name old_name alias :new_name :old_name

For methods, Module#alias_method can often be used instead of alias.

You can also use alias to alias global variables:

$old = 0 alias $new $old p $new # prints 0

You may use alias in any scope. undef The undef keyword prevents the current class from responding to calls to the named

methods.

undef my_method

Page 135: Ruby Keywords

You may use symbols instead of method names:

undef :my_method

You may undef multiple methods:

undef method1, method2

You may use undef in any scope. See also Module#undef_method defined? defined? is a keyword that returns a string describing its argument:

p defined?(UNDEFINED_CONSTANT) # prints nil p defined?(RUBY_VERSION) # prints "constant" p defined?(1 + 1) # prints "method"

You don't need to use parenthesis with defined?, but they are recommended due to

the low precedence of defined?.

For example, if you wish to check if an instance variable exists and that the instance

variable is zero:

defined? @instance_variable && @instance_variable.zero?

This returns "expression", which is not what you want if the instance variable is not

defined.

@instance_variable = 1 defined?(@instance_variable) && @instance_variable.zero?

Adding parentheses when checking if the instance variable is defined is a better check. This correctly returns nil when the instance variable is not defined

and false when the instance variable is not zero.

Using the specific reflection methods such as instance_variable_defined? for

instance variables or const_defined? for constants is less error prone than using defined?.

BEGIN and END BEGIN defines a block that is run before any other code in the current file. It is typically

used in one-liners with ruby -e. Similarly END defines a block that is run after any

other code. BEGIN must appear at top-level and END will issue a warning when you use it inside a

method.

Here is an example:

Page 136: Ruby Keywords

BEGIN { count = 0 }

You must use { and } you may not use do and end.

Here is an example one-liner that adds numbers from standard input or any files in

the argument list:

ruby -ne 'BEGIN { count = 0 }; END { puts count }; count += gets.to_i'

 

Page 137: Ruby Keywords

-module

Creates or opens a module. See modules and classes syntax  

-undef

Prevents a class or module from responding to a method call. See modules

and classes

Modules Modules serve two purposes in Ruby, namespacing and mix-in functionality.

A namespace can be used to organize code by package or functionality that

separates common names from interference by other packages. For example, the

IRB namespace provides functionality for irb that prevents a collision for the common

name “Context”.

Mix-in functionality allows sharing common methods across multiple classes or

modules. Ruby comes with the Enumerable mix-in module which provides many enumeration methods based on the each method andComparable allows comparison

of objects based on the <=> comparison method.

Note that there are many similarities between modules and classes. Besides the

ability to mix-in a module, the description of modules below also applies to classes.

Module Definition

A module is created using the module keyword:

module MyModule # ... end

A module may be reopened any number of times to add, change or remove

functionality:

module MyModule def my_method end end module MyModule alias my_alias my_method end

Page 138: Ruby Keywords

module MyModule remove_method :my_method end

Reopening classes is a very powerful feature of Ruby, but it is best to only reopen

classes you own. Reopening classes you do not own may lead to naming conflicts or

difficult to diagnose bugs.

Nesting Modules may be nested:

module Outer module Inner end end

Many packages create a single outermost module (or class) to provide a namespace

for their functionality.

You may also define inner modules using :: provided the outer modules (or classes)

are already defined:

module Outer::Inner::GrandChild end

Note that this will raise a NameError if Outer and Outer::Inner are not already

defined.

This style has the benefit of allowing the author to reduce the amount of indentation.

Instead of 3 levels of indentation only one is necessary. However, the scope of

constant lookup is different for creating a namespace using this syntax instead of the

more verbose syntax.

Scope self self refers to the object that defines the current scope. self will change when

entering a different method or when defining a new module.

Constants

Accessible constants are different depending on the module nesting (which syntax was used to define the module). In the following example the constant A::Z is

accessible from B as A is part of the nesting:

module A Z = 1

Page 139: Ruby Keywords

module B p Module.nesting #=> [A::B, A] p Z #=> 1 end end

However, if you use :: to define A::B without nesting it inside A,

a NameError exception will be raised because the nesting does not include A:

module A Z = 1 end module A::B p Module.nesting #=> [A::B] p Z #=> raises NameError end

If a constant is defined at the top-level you may preceded it with :: to reference it:

Z = 0 module A Z = 1 module B p ::Z #=> 0 end end

Methods

For method definition documentation see the syntax documentation for methods.

Class methods may be called directly. (This is slightly confusing, but a method on a

module is often called a “class method” instead of a “module method”. See

also Module#module_function which can convert an instance method into a class

method.)

When a class method references a constant, it uses the same rules as referencing it

outside the method as the scope is the same.

Instance methods defined in a module are only callable when included. These

methods have access to the constants defined when they were included through the

ancestors list:

module A Z = 1 def z Z end end

Page 140: Ruby Keywords

include A p self.class.ancestors #=> [Object, A, Kernel, BasicObject] p z #=> 1

Visibility

Ruby has three types of visibility. The default is public. A public method may be

called from any other object. The second visibility is protected. When calling a protected method the sender must

be a subclass of the receiver or the receiver must be a subclass of the sender.

Otherwise a NoMethodError will be raised. Protected visibility is most frequently used to define == and other comparison

methods where the author does not wish to expose an object's state to any caller and

would like to restrict it only to inherited classes.

Here is an example:

class A def n(other) other.m end end class B < A def m 1 end protected :m end class C < B end a = A.new b = B.new c = C.new c.n b #=> 1 -- C is a subclass of B b.n b #=> 1 -- m called on defining class a.n b # raises NoMethodError A is not a subclass of B

The third visibility is private. A private method may not be called with a receiver, not

even self. If a private method is called with a receiver a NoMethodError will be

raised.

Page 141: Ruby Keywords

alias and undef You may also alias or undefine methods, but these operations are not restricted to

modules or classes. See the miscellaneous syntax section for documentation.

Classes Every class is also a module, but unlike modules a class may not be mixed-in to

another module (or class). Like a module, a class can be used as a namespace. A

class also inherits methods and constants from its superclass.

Defining a class Use the class keyword to create a class:

class MyClass # ... end

If you do not supply a superclass your new class will inherit from Object. You may inherit from a different class using < followed by a class name:

class MySubclass < MyClass # ... end

There is a special class BasicObject which is designed as a blank class and includes

a minimum of built-in methods. You can use BasicObject to create an independent

inheritance structure. See the BasicObjectdocumentation for further details.

Inheritance Any method defined on a class is callable from its subclass:

class A Z = 1 def z Z end end class B < A end p B.new.z #=> 1

Page 142: Ruby Keywords

The same is true for constants:

class A Z = 1 end class B < A def z Z end end p B.new.z #=> 1

You can override the functionality of a superclass method by redefining the method:

class A def m 1 end end class B < A def m 2 end end p B.new.m #=> 2

If you wish to invoke the superclass functionality from a method use super:

class A def m 1 end end class B < A def m 2 + super end end p B.new.m #=> 3

When used without any arguments super uses the arguments given to the subclass

method. To send no arguments to the superclass method use super(). To send

specific arguments to the superclass method provide them manually like super(2).

super may be called as many times as you like in the subclass method.

Page 143: Ruby Keywords

Singleton Classes The singleton class (also known as the metaclass or eigenclass) of an object is a

class that holds methods for only that instance. You can access the singleton class of an object using class << object like this:

class C end class << C # self is the singleton class here end

Most frequently you'll see the singleton class accessed like this:

class C class << self # ... end end

This allows definition of methods and attributes on a class (or module) without needing to write def self.my_method.

Since you can open the singleton class of any object this means that this code block:

o = Object.new def o.my_method 1 + 1 end

is equivalent to this code block:

o = Object.new class << o def my_method 1 + 1 end end

Both objects will have a my_method that returns 2.  

 

 

 

 

 

Page 144: Ruby Keywords

class Module A Module is a collection of methods and constants. The methods in a module may be instance

methods or module methods. Instance methods appear as methods in a class when the module

is included, module methods do not. Conversely, module methods may be called without

creating an encapsulating object, while instance methods may not.

(See Module#module_function.)

In the descriptions that follow, the parameter sym refers to a symbol, which is either a quoted

string or a Symbol (such as :name).

module Mod include Math CONST = 1 def meth # ... end end Mod.class #=> Module Mod.constants #=> [:CONST, :PI, :E] Mod.instance_methods #=> [:meth]

Public Class Methods

constants → array constants(inherited) → array In the first form, returns an array of the names of all constants accessible from the point of

call. This list includes the names of all modules and classes defined in the global scope.

Module.constants.first(4) # => [:ARGF, :ARGV, :ArgumentError, :Array] Module.constants.include?(:SEEK_SET) # => false class IO Module.constants.include?(:SEEK_SET) # => true end

The second form calls the instance method constants.

nesting → array Returns the list of Modules nested at the point of call.

module M1 module M2 $a = Module.nesting end end $a #=> [M1::M2, M1] $a[0].name #=> "M1::M2"

Page 145: Ruby Keywords

new → mod new {|mod| block } → mod Creates a new anonymous module. If a block is given, it is passed the module object, and the

block is evaluated in the context of this module using module_eval.

fred = Module.new do def meth1 "hello" end def meth2 "bye" end end a = "my string" a.extend(fred) #=> "my string" a.meth1 #=> "hello" a.meth2 #=> "bye"

Assign the module to a constant (name starting uppercase) if you want to treat it like a regular

module.

Public Instance Methods

mod < other → true, false, or nil Returns true if mod is a subclass of other. Returns nil if there's no relationship between the

two. (Think of the relationship in terms of the class definition: “class A<B” implies “A<B”.)

mod <= other → true, false, or nil Returns true if mod is a subclass of other or is the same as other. Returns nil if there's no

relationship between the two. (Think of the relationship in terms of the class definition: “class

A<B” implies “A<B”.)

module <=> other_module → -1, 0, +1, or nil Comparison—Returns -1, 0, +1 or nil depending on whether module includes other_module,

they are the same, or if module is included by other_module.

Returns nil if module has no relationship with other_module, if other_module is not a

module, or if the two values are incomparable.

obj == other → true or false equal?(other) → true or false eql?(other) → true or false Equality — At the Object level, == returns true only if obj and other are the same object.

Typically, this method is overridden in descendant classes to provide class-specific meaning.

Unlike ==, the equal? method should never be overridden by subclasses as it is used to

determine object identity (that is, a.equal?(b) if and only if a is the same object as b):

obj = "a" other = obj.dup obj == other #=> true

Page 146: Ruby Keywords

obj.equal? other #=> false obj.equal? obj #=> true

The eql? method returns true if obj and other refer to the same hash key. This is used

by Hash to test members for equality. For objects of class Object, eql? is synonymous

with ==. Subclasses normally continue this tradition by aliasing eql? to their

overridden == method, 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

mod === obj → true or false Case Equality—Returns true if obj is an instance of mod or and instance of one of mod's

descendants. Of limited use for modules, but can be used in case statements to classify

objects by class.

mod > other → true, false, or nil Returns true if mod is an ancestor of other. Returns nil if there's no relationship between the

two. (Think of the relationship in terms of the class definition: “class A<B” implies “B>A”.)

mod >= other → true, false, or nil Returns true if mod is an ancestor of other, or the two modules are the same. Returns nil if

there's no relationship between the two. (Think of the relationship in terms of the class

definition: “class A<B” implies “B>A”.)

ancestors → array Returns a list of modules included/prepended in mod (including mod itself).

module Mod include Math include Comparable prepend Enumerable end Mod.ancestors #=> [Enumerable, Mod, Comparable, Math] Math.ancestors #=> [Math] Enumerable.ancestors #=> [Enumerable]

autoload(module, filename) → nil Registers filename to be loaded (using Kernel::require) the first time that module (which

may be a String or a symbol) is accessed in the namespace of mod.

module A end A.autoload(:B, "b") A::B.doit # autoloads "b"

autoload?(name) → String or nil

Page 147: Ruby Keywords

Returns filename to be loaded if name is registered as autoload in the namespace of mod.

module A end A.autoload(:B, "b") A.autoload?(:B) #=> "b"

class_eval(string [, filename [, lineno]]) → obj Evaluates the string or block in the context of mod, except that when a block is given,

constant/class variable lookup is not affected. This can be used to add methods to a

class. module_eval returns the result of evaluating its argument. The

optional filename and lineno parameters set the text for error messages.

class Thing end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123)

produces:

Hello there!

dummy:123:in `module_eval': undefined local variable

or method `code' for Thing:Class

class_exec(arg...) {|var...| block } → obj Evaluates the given block in the context of the class/module. The method defined in the block

will belong to the receiver. Any arguments passed to the method will be passed to the block.

This can be used if the block needs to access instance variables.

class Thing end Thing.class_exec{ def hello() "Hello there!" end } puts Thing.new.hello()

produces:

Hello there!

class_variable_defined?(symbol) → true or false class_variable_defined?(string) → true or false Returns true if the given class variable is defined in obj. String arguments are converted to

symbols.

class Fred

Page 148: Ruby Keywords

@@foo = 99 end Fred.class_variable_defined?(:@@foo) #=> true Fred.class_variable_defined?(:@@bar) #=> false

class_variable_get(symbol) → obj class_variable_get(string) → obj Returns the value of the given class variable (or throws a NameError exception). The @@ part

of the variable name should be included for regular class variables. String arguments are

converted to symbols.

class Fred @@foo = 99 end Fred.class_variable_get(:@@foo) #=> 99

class_variable_set(symbol, obj) → obj class_variable_set(string, obj) → obj Sets the class variable named by symbol to the given object. If the class variable name is

passed as a string, that string is converted to a symbol.

class Fred @@foo = 99 def foo @@foo end end Fred.class_variable_set(:@@foo, 101) #=> 101 Fred.new.foo #=> 101

class_variables(inherit=true) → array Returns an array of the names of class variables in mod. This includes the names of class

variables in any included modules, unless the inherit parameter is set to false.

class One @@var1 = 1 end class Two < One @@var2 = 2 end One.class_variables #=> [:@@var1] Two.class_variables #=> [:@@var2, :@@var1] Two.class_variables(false) #=> [:@@var2]

const_defined?(sym, inherit=true) → true or false const_defined?(str, inherit=true) → true or false Says whether mod or its ancestors have a constant with the given name:

Float.const_defined?(:EPSILON) #=> true, found in Float itself Float.const_defined?("String") #=> true, found in Object (ancestor) BasicObject.const_defined?(:Hash) #=> false

Page 149: Ruby Keywords

If mod is a Module, additionally Object and its ancestors are checked:

Math.const_defined?(:String) #=> true, found in Object

In each of the checked classes or modules, if the constant is not present but there is an

autoload for it, true is returned directly without autoloading:

module Admin autoload :User, 'admin/user' end Admin.const_defined?(:User) #=> true

If the constant is not found the callback const_missing is not called and the method

returns false.

If inherit is false, the lookup only checks the constants in the receiver:

IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor) IO.const_defined?(:SYNC, false) #=> false, not found in IO itself

In this case, the same logic for autoloading applies.

If the argument is not a valid constant name a NameError is raised with the message “wrong

constant name name”:

Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar

const_get(sym, inherit=true) → obj const_get(str, inherit=true) → obj Checks for a constant with the given name in mod. If inherit is set, the lookup will also

search the ancestors (and Object if mod is a Module).

The value of the constant is returned if a definition is found, otherwise a NameError is raised.

Math.const_get(:PI) #=> 3.14159265358979

This method will recursively look up constant names if a namespaced class name is provided.

For example:

module Foo; class Bar; end end Object.const_get 'Foo::Bar'

The inherit flag is respected on each lookup. For example:

module Foo class Bar VAL = 10 end class Baz < Bar; end end Object.const_get 'Foo::Baz::VAL' # => 10

Page 150: Ruby Keywords

Object.const_get 'Foo::Baz::VAL', false # => NameError

If the argument is not a valid constant name a NameError will be raised with a warning

“wrong constant name”.

Object.const_get 'foobar' #=> NameError: wrong constant name foobar

const_missing(sym) → obj Invoked when a reference is made to an undefined constant in mod. It is passed a symbol for

the undefined constant, and returns a value to be used for that constant. The following code is

an example of the same:

def Foo.const_missing(name) name # return the constant name as Symbol end Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned

In the next example when a reference is made to an undefined constant, it attempts to load a

file whose name is the lowercase version of the constant (thus class Fred is assumed to be in

file fred.rb). If found, it returns the loaded class. It therefore implements an autoload feature

similar to Kernel#autoload and #autoload.

def Object.const_missing(name) @looked_for ||= {} str_name = name.to_s raise "Class not found: #{name}" if @looked_for[str_name] @looked_for[str_name] = 1 file = str_name.downcase require file klass = const_get(name) return klass if klass raise "Class not found: #{name}" end

const_set(sym, obj) → obj const_set(str, obj) → obj Sets the named constant to the given object, returning that object. Creates a new constant if no

constant with the given name previously existed.

Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714 Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968

If sym or str is not a valid constant name a NameError will be raised with a warning “wrong

constant name”.

Object.const_set('foobar', 42) #=> NameError: wrong constant name foobar

constants(inherit=true) → array

Page 151: Ruby Keywords

Returns an array of the names of the constants accessible in mod. This includes the names of

constants in any included modules (example at start of section), unless the inherit parameter is

set to false.

The implementation makes no guarantees about the order in which the constants are yielded.

IO.constants.include?(:SYNC) #=> true IO.constants(false).include?(:SYNC) #=> false

Also see Module::const_defined?.

deprecate_constant(*args)

freeze → mod Prevents further modifications to mod.

This method returns self.

include(module, ...) → self Invokes Module.append_features on each parameter in reverse order.

include?(module) → true or false Returns true if module is included in mod or one of mod's ancestors.

module A end class B include A end class C < B end B.include?(A) #=> true C.include?(A) #=> true A.include?(A) #=> false

included_modules → array Returns the list of modules included in mod.

module Mixin end module Outer include Mixin end Mixin.included_modules #=> [] Outer.included_modules #=> [Mixin]

inspect() Alias for: to_s

instance_method(symbol) → unbound_method Returns an UnboundMethod representing the given instance method in mod.

class Interpreter

Page 152: Ruby Keywords

def do_a() print "there, "; end def do_d() print "Hello "; end def do_e() print "!\n"; end def do_v() print "Dave"; end Dispatcher = { "a" => instance_method(:do_a), "d" => instance_method(:do_d), "e" => instance_method(:do_e), "v" => instance_method(:do_v) } def interpret(string) string.each_char {|b| Dispatcher[b].bind(self).call } end end interpreter = Interpreter.new interpreter.interpret('dave')

produces:

Hello there, Dave!

instance_methods(include_super=true) → array Returns an array containing the names of the public and protected instance methods in the

receiver. For a module, these are the public and protected methods; for a class, they are the

instance (not singleton) methods. If the optional parameter is false, the methods of any

ancestors are not included.

module A def method1() end end class B include A def method2() end end class C < B def method3() end end A.instance_methods(false) #=> [:method1] B.instance_methods(false) #=> [:method2] B.instance_methods(true).include?(:method1) #=> true C.instance_methods(false) #=> [:method3] C.instance_methods.include?(:method2) #=> true

method_defined?(symbol) → true or false method_defined?(string) → true or false Returns true if the named method is defined by mod (or its included modules and, if mod is a

class, its ancestors). Public and protected methods are matched. String arguments are

converted to symbols.

module A def method1() end def protected_method1() end protected :protected_method1

Page 153: Ruby Keywords

end class B def method2() end def private_method2() end private :private_method2 end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.method_defined? "method1" #=> true C.method_defined? "method2" #=> true C.method_defined? "method3" #=> true C.method_defined? "protected_method1" #=> true C.method_defined? "method4" #=> false C.method_defined? "private_method2" #=> false

module_eval {|| block } → obj Evaluates the string or block in the context of mod, except that when a block is given,

constant/class variable lookup is not affected. This can be used to add methods to a

class. module_eval returns the result of evaluating its argument. The

optional filename and lineno parameters set the text for error messages.

class Thing end a = %q{def hello() "Hello there!" end} Thing.module_eval(a) puts Thing.new.hello() Thing.module_eval("invalid code", "dummy", 123)

produces:

Hello there!

dummy:123:in `module_eval': undefined local variable

or method `code' for Thing:Class

module_exec(arg...) {|var...| block } → obj Evaluates the given block in the context of the class/module. The method defined in the block

will belong to the receiver. Any arguments passed to the method will be passed to the block.

This can be used if the block needs to access instance variables.

class Thing end Thing.class_exec{ def hello() "Hello there!" end } puts Thing.new.hello()

Page 154: Ruby Keywords

produces:

Hello there!

name → string Returns the name of the module mod. Returns nil for anonymous modules.

prepend(module, ...) → self Invokes Module.prepend_features on each parameter in reverse order.

private_class_method(symbol, ...) → mod private_class_method(string, ...) → mod Makes existing class methods private. Often used to hide the default constructor new.

String arguments are converted to symbols.

class SimpleSingleton # Not thread safe private_class_method :new def SimpleSingleton.create(*args, &block) @me = new(*args, &block) if ! @me @me end end

private_constant(symbol, ...) → mod Makes a list of existing constants private.

private_instance_methods(include_super=true) → array Returns a list of the private instance methods defined in mod. If the optional parameter

is false, the methods of any ancestors are not included.

module Mod def method1() end private :method1 def method2() end end Mod.instance_methods #=> [:method2] Mod.private_instance_methods #=> [:method1]

private_method_defined?(symbol) → true or false private_method_defined?(string) → true or false Returns true if the named private method is defined by _ mod_ (or its included modules and,

if mod is a class, its ancestors). String arguments are converted to symbols.

module A def method1() end end class B private def method2() end end class C < B include A def method3() end

Page 155: Ruby Keywords

end A.method_defined? :method1 #=> true C.private_method_defined? "method1" #=> false C.private_method_defined? "method2" #=> true C.method_defined? "method2" #=> false

protected_instance_methods(include_super=true) → array Returns a list of the protected instance methods defined in mod. If the optional parameter

is false, the methods of any ancestors are not included.

protected_method_defined?(symbol) → true or false protected_method_defined?(string) → true or false Returns true if the named protected method is defined by mod (or its included modules and,

if mod is a class, its ancestors). String arguments are converted to symbols.

module A def method1() end end class B protected def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.protected_method_defined? "method1" #=> false C.protected_method_defined? "method2" #=> true C.method_defined? "method2" #=> true

psych_yaml_as(url) Also aliased as: yaml_as

public_class_method(symbol, ...) → mod public_class_method(string, ...) → mod Makes a list of existing class methods public.

String arguments are converted to symbols.

public_constant(symbol, ...) → mod Makes a list of existing constants public.

public_instance_method(symbol) → unbound_method Similar to instance_method, searches public method only.

public_instance_methods(include_super=true) → array Returns a list of the public instance methods defined in mod. If the optional parameter

is false, the methods of any ancestors are not included.

public_method_defined?(symbol) → true or false

Page 156: Ruby Keywords

public_method_defined?(string) → true or false Returns true if the named public method is defined by mod (or its included modules and,

if mod is a class, its ancestors). String arguments are converted to symbols.

module A def method1() end end class B protected def method2() end end class C < B include A def method3() end end A.method_defined? :method1 #=> true C.public_method_defined? "method1" #=> true C.public_method_defined? "method2" #=> false C.method_defined? "method2" #=> true

remove_class_variable(sym) → obj Removes the definition of the sym, returning that constant's value.

class Dummy @@var = 99 puts @@var remove_class_variable(:@@var) p(defined? @@var) end

produces:

99 nil

singleton_class? → true or false Returns true if mod is a singleton class or false if it is an ordinary class or module.

class C end C.singleton_class? #=> false C.singleton_class.singleton_class? #=> true

to_s → string Returns a string representing this module or class. For basic classes and modules, this is the

name. For singletons, we show information on the thing we're attached to as well.

Also aliased as: inspect

yaml_as(url) Alias for: psych_yaml_as

Page 157: Ruby Keywords

Private Instance Methods

alias_method(new_name, old_name) → self Makes new_name a new copy of the method old_name. This can be used to retain access to

methods that are overridden.

module Mod alias_method :orig_exit, :exit def exit(code=0) puts "Exiting with code #{code}" orig_exit(code) end end include Mod exit(99)

produces:

Exiting with code 99

append_features(mod) → mod When this module is included in another, Ruby calls append_features in this module,

passing it the receiving module in mod. Ruby's default implementation is to add the constants,

methods, and module variables of this module to mod if this module has not already been

added to mod or one of its ancestors. See also Module#include.

attr(*args)

attr_accessor(symbol, ...) → nil attr_accessor(string, ...) → nil Defines a named attribute for this module, where the name is symbol.id2name, creating an

instance variable (@name) and a corresponding access method to read it. Also creates a method

called name= to set the attribute. String arguments are converted to symbols.

module Mod attr_accessor(:one, :two) end Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]

attr_reader(symbol, ...) → nil attr(symbol, ...) → nil attr_reader(string, ...) → nil attr(string, ...) → nil Creates instance variables and corresponding methods that return the value of each instance

variable. Equivalent to calling “attr:name'' on each name in turn. String arguments are

converted to symbols.

attr_writer(symbol, ...) → nil attr_writer(string, ...) → nil

Page 158: Ruby Keywords

Creates an accessor method to allow assignment to the attribute symbol.id2name. String

arguments are converted to symbols.

define_method(symbol, method) → symbol define_method(symbol) { block } → symbol Defines an instance method in the receiver. The method parameter can be a Proc, a Method or

an UnboundMethod object. If a block is specified, it is used as the method body. This block is

evaluated using instance_eval, a point that is tricky to demonstrate

because define_method is private. (This is why we resort to the send hack in this example.)

class A def fred puts "In Fred" end def create_method(name, &block) self.class.send(:define_method, name, &block) end define_method(:wilma) { puts "Charge it!" } end class B < A define_method(:barney, instance_method(:fred)) end a = B.new a.barney a.wilma a.create_method(:betty) { p self } a.betty

produces:

In Fred Charge it! #<B:0x401b39e8>

extend_object(obj) → obj 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 puts "Can't add Picky to a String" else puts "Picky added to #{o.class}" super end end end (s = Array.new).extend Picky # Call Object.extend (s = "quick brown fox").extend Picky

produces:

Picky added to Array

Page 159: Ruby Keywords

Can't add Picky to a String

extended(othermod) The equivalent of included, but for extended modules.

module A def self.extended(mod) puts "#{self} extended in #{mod}" end end module Enumerable extend A end # => prints "A extended in Enumerable"

included(othermod) Callback invoked whenever the receiver is included in another module or class. This should

be used in preference to Module.append_features if your code wants to perform some

action when a module is included in another.

module A def A.included(mod) puts "#{self} included in #{mod}" end end module Enumerable include A end # => prints "A included in Enumerable"

method_added(method_name) Invoked as a callback whenever an instance method is added to the receiver.

module Chatty def self.method_added(method_name) puts "Adding #{method_name.inspect}" end def self.some_class_method() end def some_instance_method() end end

produces:

Adding :some_instance_method

method_removed(method_name) Invoked as a callback whenever an instance method is removed from the receiver.

module Chatty def self.method_removed(method_name) puts "Removing #{method_name.inspect}" end

Page 160: Ruby Keywords

def self.some_class_method() end def some_instance_method() end class << self remove_method :some_class_method end remove_method :some_instance_method end

produces:

Removing :some_instance_method

method_undefined(p1) Not documented

module_function(symbol, ...) → self module_function(string, ...) → self Creates module functions for the named methods. These functions may be called with the

module as a receiver, and also become available as instance methods to classes that mix in the

module. Module functions are copies of the original, and so may be changed independently.

The instance-method versions are made private. If used with no arguments, subsequently

defined methods become module functions. String arguments are converted to symbols.

module Mod def one "This is one" end module_function :one end class Cls include Mod def call_one one end end Mod.one #=> "This is one" c = Cls.new c.call_one #=> "This is one" module Mod def one "This is the new one" end end Mod.one #=> "This is one" c.call_one #=> "This is the new one"

prepend_features(mod) → mod When this module is prepended in another, Ruby calls prepend_features in this module,

passing it the receiving module in mod. Ruby's default implementation is to overlay the

constants, methods, and module variables of this module to mod if this module has not already

been added to mod or one of its ancestors. See also Module#prepend.

prepended(othermod)

Page 161: Ruby Keywords

The equivalent of included, but for prepended modules.

module A def self.prepended(mod) puts "#{self} prepended to #{mod}" end end module Enumerable prepend A end # => prints "A prepended to Enumerable"

private → self private(symbol, ...) → self private(string, ...) → self With no arguments, sets the default visibility for subsequently defined methods to private.

With arguments, sets the named methods to have private visibility. String arguments are

converted to symbols.

module Mod def a() end def b() end private def c() end private :a end Mod.private_instance_methods #=> [:a, :c]

protected → self protected(symbol, ...) → self protected(string, ...) → self With no arguments, sets the default visibility for subsequently defined methods to protected.

With arguments, sets the named methods to have protected visibility. String arguments are

converted to symbols.

public → self public(symbol, ...) → self public(string, ...) → self With no arguments, sets the default visibility for subsequently defined methods to public.

With arguments, sets the named methods to have public visibility. String arguments are

converted to symbols.

refine(klass) { block } → module Refine klass in the receiver.

Returns an overlaid module.

remove_const(sym) → obj Removes the definition of the given constant, returning that constant's previous value. If that

constant referred to a module, this will not change that module's name and can lead to

confusion.

Page 162: Ruby Keywords

remove_method(symbol) → self remove_method(string) → self Removes the method identified by symbol from the current class. For an example,

see Module.undef_method. String arguments are converted to symbols.

undef_method(symbol) → self undef_method(string) → self Prevents the current class from responding to calls to the named method. Contrast this

with remove_method, which deletes the method from the particular class; Ruby will still

search superclasses and mixed-in modules for a possible receiver. String arguments are

converted to symbols.

class Parent def hello puts "In parent" end end class Child < Parent def hello puts "In child" end end c = Child.new c.hello class Child remove_method :hello # remove from child, still in parent end c.hello class Child undef_method :hello # prevent any calls to 'hello' end c.hello

produces:

In child

In parent

prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError)

using(module) → self Import class refinements from module into the current class or module definition.

 

 

 

 

Page 163: Ruby Keywords

module Singleton The Singleton module implements the Singleton pattern.

Usage To use Singleton, include the module in your class.

class Klass include Singleton # ... end

This ensures that only one instance of Klass can be created.

a,b = Klass.instance, Klass.instance a == b # => true Klass.new # => NoMethodError - new is private ...

The instance is created at upon the first call of Klass.instance().

class OtherKlass include Singleton # ... end ObjectSpace.each_object(OtherKlass){} # => 0 OtherKlass.instance ObjectSpace.each_object(OtherKlass){} # => 1

This behavior is preserved under inheritance and cloning.

Implementation This above is achieved by:

Making Klass.new and Klass.allocate private.

Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that

the Singleton properties are kept when inherited and cloned.

Providing the Klass.instance() method that returns the same object each time it is

called.

Overriding Klass._load(str) to call Klass.instance().

Page 164: Ruby Keywords

Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent cloning or

duping.

Singleton and Marshal By default Singleton's #_dump(depth) returns the empty string. Marshalling by default will

strip state information, e.g. instance variables and taint state, from the instance. Classes

using Singleton can provide custom _load(str) and _dump(depth) methods to retain some of

the previous state of the instance.

require 'singleton' class Example include Singleton attr_accessor :keep, :strip def _dump(depth) # this strips the @strip information from the instance Marshal.dump(@keep, depth) end def self._load(str) instance.keep = Marshal.load(str) instance end end a = Example.instance a.keep = "keep this" a.strip = "get rid of this" a.taint stored_state = Marshal.dump(a) a.keep = nil a.strip = nil b = Marshal.load(stored_state) p a == b # => true p a.keep # => "keep this" p a.strip # => nil

Public Class Methods

_load()

By default calls instance(). Override to retain singleton state.

Private Class Methods

append_features(mod)

Calls superclass method

included(klass)

Page 165: Ruby Keywords

Calls superclass method

Public Instance Methods

_dump(depth = -1)

By default, do not retain any state when marshalling.

clone()

Raises a TypeError to prevent cloning. dup()

Raises a TypeError to prevent duping.  

Page 166: Ruby Keywords

-for A loop that is similar to using the each method. See control expressions

-if Used for if and modifier if expressions. See control expressions

-in Used to separate the iterable object and iterator variable in a for loop. See control expressions

-next

Skips the rest of the block. See control expressions

-redo

Restarts execution in the current block. See control expressions

-then

Indicates the end of conditional blocks in control structures. See control expressions

-unless

Used for unless and modifier unless expressions. See control expressions

-until

Creates a loop that executes until the condition is true. See control expressions

-when

A condition in a case expression. See control expressions

-while

Creates a loop that executes while the condition is true. See control expressions

 

Page 167: Ruby Keywords

Control Expressions Ruby has a variety of ways to control execution. All the expressions described here

return a value.

For the tests in these control expressions, nil and false are false-values

and true and any other object are true-values. In this document “true” will mean

“true-value” and “false” will mean “false-value”.

if Expression The simplest if expression has two parts, a “test” expression and a “then”

expression. If the “test” expression evaluates to a true then the “then” expression is

evaluated.

Here is a simple if statement:

if true then puts "the test resulted in a true-value" end

This will print “the test resulted in a true-value”.

The then is optional:

if true puts "the test resulted in a true-value" end

This document will omit the optional then for all expressions as that is the most

common usage of if.

You may also add an else expression. If the test does not evaluate to true

the else expression will be executed:

if false puts "the test resulted in a true-value" else puts "the test resulted in a false-value" end

This will print “the test resulted in a false-value”.

You may add an arbitrary number of extra tests to an if expression using elsif.

An elsif executes when all tests above the elsif are false.

a = 1 if a == 0 puts "a is zero" elsif a == 1 puts "a is one" else

Page 168: Ruby Keywords

puts "a is some other value" end

This will print “a is one” as 1 is not equal to 0. Since else is only executed when there

are no matching conditions. Once a condition matches, either the if condition or any elsif condition,

the if expression is complete and no further tests will be performed.

Like an if, an elsif condition may be followed by a then.

In this example only “a is one” is printed:

a = 1 if a == 0 puts "a is zero" elsif a == 1 puts "a is one" elsif a >= 1 puts "a is greater than or equal to one" else puts "a is some other value" end

The tests for if and elsif may have side-effects. The most common use of side-

effect is to cache a value into a local variable:

if a = object.some_value # do something to a end

The result value of an if expression is the last value executed in the expression.

Ternary if You may also write a if-then-else expression using ? and :. This ternary if:

input_type = gets =~ /hello/i ? "greeting" : "other"

Is the same as this if expression:

input_type = if gets =~ /hello/i "greeting" else "other" end

While the ternary if is much shorter to write than the more verbose form, for

readability it is recommended that the ternary if is only used for simple conditionals.

Page 169: Ruby Keywords

Also, avoid using multiple ternary conditions in the same expression as this can be

confusing.

unless Expression The unless expression is the opposite of the if expression. If the value is false, the

“then” expression is executed:

unless true puts "the value is a false-value" end

This prints nothing as true is not a false-value.

You may use an optional then with unless just like if.

Note that the above unless expression is the same as:

if not true puts "the value is a false-value" end

Like an if expression you may use an else condition with unless:

unless true puts "the value is false" else puts "the value is true" end

This prints “the value is true” from the else condition.

You may not use elsif with an unless expression.

The result value of an unless expression is the last value executed in the expression.

Modifier if and unless if and unless can also be used to modify an expression. When used as a modifier

the left-hand side is the “then” expression and the right-hand side is the “test”

expression:

a = 0 a += 1 if a.zero? p a

This will print 1.

a = 0

Page 170: Ruby Keywords

a += 1 unless a.zero? p a

This will print 0.

While the modifier and standard versions have both a “test” expression and a “then”

expression, they are not exact transformations of each other due to parse order. Here

is an example that shows the difference:

p a if a = 0.zero?

This raises the NameError “undefined local variable or method `a'”. When ruby parses this expression it first encounters a as a method call in the “then”

expression, then later it sees the assignment to a in the “test” expression and

marks a as a local variable.

When running this line it first executes the “test” expression, a = 0.zero?.

Since the test is true it executes the “then” expression, p a. Since the a in the body

was recorded as a method which does not exist the NameError is raised. The same is true for unless.

case Expression The case expression can be used in two ways.

The most common way is to compare an object against multiple patterns. The

patterns are matched using the +===+ method which is aliased to +==+ on Object.

Other classes must override it to give meaningful behavior.

SeeModule#=== and Regexp#=== for examples. Here is an example of using case to compare a String against a pattern:

case "12345" when /^1/ puts "the string starts with one" else puts "I don't know what the string starts with" end

Here the string "12345" is compared with /^1/ by calling /^1/ === "12345" which

returns true. Like the if expression, the first when that matches is executed and all

other matches are ignored. If no matches are found, the else is executed.

The else and then are optional, this case expression gives the same result as the

one above:

case "12345"

Page 171: Ruby Keywords

when /^1/ puts "the string starts with one" end

You may place multiple conditions on the same when:

case "2" when /^1/, "2" puts "the string starts with one or is '2'" end

Ruby will try each condition in turn, so first /^1/ === "2" returns false, then "2" ===

"2" returns true, so “the string starts with one or is '2'” is printed.

You may use then after the when condition. This is most frequently used to place the

body of the when on a single line.

case a

when 1, 2 then puts "a is one or two

when 3 then puts "a is three"

else puts "I don't know what a is"

end

The other way to use a case expression is like an if-elsif expression:

a = 2 case when a == 1, a == 2 puts "a is one or two" when a == 3 puts "a is three" else puts "I don't know what a is" end

Again, the then and else are optional.

The result value of a case expression is the last value executed in the expression.

while Loop The while loop executes while a condition is true:

a = 0 while a < 10 do p a

Page 172: Ruby Keywords

a += 1 end p a

Prints the numbers 0 through 10. The condition a < 10 is checked before the loop is

entered, then the body executes, then the condition is checked again. When the

condition results in false the loop is terminated. The do keyword is optional. The following loop is equivalent to the loop above:

while a < 10 p a a += 1 end

The result of a while loop is nil unless break is used to supply a value.

until Loop The until loop executes while a condition is false:

a = 0 until a > 10 do p a a += 1 end p a

This prints the numbers 0 through 11. Like a while loop the condition a > 10 is

checked when entering the loop and each time the loop body executes. If the

condition is false the loop will continue to execute. Like a while loop, the do is optional.

Like a while loop, the result of an until loop is nil unless break is used.

for Loop The for loop consists of for followed by a variable to contain the iteration argument

followed by in and the value to iterate over using each. The do is optional:

for value in [1, 2, 3] do puts value end

Prints 1, 2 and 3.

Like while and until, the do is optional.

The for loop is similar to using each, but does not create a new variable scope.

The result value of a for loop is the value iterated over unless break is used.

Page 173: Ruby Keywords

The for loop is rarely used in modern ruby programs.

Modifier while and until Like if and unless, while and until can be used as modifiers:

a = 0 a += 1 while a < 10 p a # prints 10

until used as a modifier:

a = 0 a += 1 until a > 10 p a # prints 11

You can use begin and end to create a while loop that runs the body once before the

condition:

a = 0 begin a += 1 end while a < 10 p a # prints 10

If you don't use rescue or ensure, Ruby optimizes away any exception handling

overhead.

break Statement Use break to leave a block early. This will stop iterating over the items in values if

one of them is even:

values.each do |value| break if value.even? # ... end

You can also terminate from a while loop using break:

a = 0

Page 174: Ruby Keywords

while true do p a a += 1 break if a < 10 end p a

This prints the numbers 0 and 1.

break accepts a value that supplies the result of the expression it is “breaking” out of:

result = [1, 2, 3].each do |value| break value * 2 if value.even? end p result # prints 4

next Statement Use next to skip the rest of the current iteration:

result = [1, 2, 3].map do |value| next if value.even? value * 2 end p result # prints [2, nil, 6]

next accepts an argument that can be used the result of the current block iteration:

result = [1, 2, 3].map do |value| next value if value.even? value * 2 end p result # prints [2, 2, 6]

redo Statement Use redo to redo the current iteration:

result = [] while result.length < 10 do result << result.length redo if result.last.even? result << result.length + 1 end

Page 175: Ruby Keywords

p result

This prints [0, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]

In Ruby 1.8, you could also use retry where you used redo. This is no longer true,

now you will receive a SyntaxError when you use retry outside of a rescue block.

See Exceptions for proper usage of retry.

Flip-Flop The flip-flop is a rarely seen conditional expression. It's primary use is for processing text from ruby one-line programs used with ruby -n or ruby -p.

The form of the flip-flop is an expression that indicates when the flip-flop turns on, .. (or ...), then an expression that indicates when the flip-flop will turn off. While

the flip-flop is on it will continue to evaluate to true, andfalse when off.

Here is an example:

selected = [] 0.upto 10 do |value| selected << value if value==2..value==8 end p selected # prints [2, 3, 4, 5, 6, 7, 8]

In the above example, the on condition is n==2. The flip-flop is initially off (false) for 0

and 1, but becomes on (true) for 2 and remains on through 8. After 8 it turns off and

remains off for 9 and 10. The flip-flop must be used inside a conditional such as if, while, unless, until etc.

including the modifier forms. When you use an inclusive range (..), the off condition is evaluated when the on

condition changes:

selected = [] 0.upto 5 do |value| selected << value if value==2..value==2 end p selected # prints [2]

Here, both sides of the flip-flop are evaluated so the flip-flop turns on and off only when value equals 2. Since the flip-flop turned on in the iteration it returns true.

When you use an exclusive range (...), the off condition is evaluated on the

following iteration:

selected = []

Page 176: Ruby Keywords

0.upto 5 do |value| selected << value if value==2...value==2 end p selected # prints [2, 3, 4, 5]

Here, the flip-flop turns on when value equals 2, but doesn't turn off on the same

iteration. The off condition isn't evaluated until the following iteration and value will

never be two again.  

Page 177: Ruby Keywords

-false Boolean false. See literals

-nil A false value usually indicating “no value” or “unknown”. See literals

-true Boolean true. See literals

 

Literals Literals create objects you can use in your program. Literals include:

Booleans and nil

Numbers

Strings

Symbols

Arrays

Hashes

Ranges

Regular Expressions

Procs

Booleans and nil nil and false are both false values. nil is sometimes used to indicate “no value” or

“unknown” but evaluates to false in conditional expressions.

true is a true value. All objects except nil and false evaluate to a true value in

conditional expressions. (There are also the constants TRUE, FALSE and NIL, but the lowercase literal forms are

preferred.)

Page 178: Ruby Keywords

Numbers You can write integers of any size as follows:

1234 1_234

These numbers have the same value, 1,234. The underscore may be used to

enhance readability for humans. You may place an underscore anywhere in the

number.

Floating point numbers may be written as follows:

12.34 1234e-2 1.234E1

These numbers have the same value, 12.34. You may use underscores in floating

point numbers as well.

You can use a special prefix to write numbers in decimal, hexadecimal, octal or binary formats. For decimal numbers use a prefix of 0d, for hexadecimal numbers use

a prefix of 0x, for octal numbers use a prefix of 0 or 0o, for binary numbers use a

prefix of 0b. The alphabetic component of the number is not case-sensitive.

Examples:

0d170 0D170 0xaa 0xAa 0xAA 0Xaa 0XAa 0XaA 0252 0o252 0O252 0b10101010 0B10101010

All these numbers have the same decimal value, 170. Like integers and floats you

may use an underscore for readability.

Strings The most common way of writing strings is using ":

"This is a string."

Page 179: Ruby Keywords

The string may be many lines long.

Any internal " must be escaped:

"This string has a quote: \". As you can see, it is escaped"

Double-quote strings allow escaped characters such as \n for newline, \t for tab, etc.

The full list of supported escape sequences are as follows:

\a bell, ASCII 07h (BEL)

\b backspace, ASCII 08h (BS)

\t horizontal tab, ASCII 09h (TAB)

\n newline (line feed), ASCII 0Ah (LF)

\v vertical tab, ASCII 0Bh (VT)

\f form feed, ASCII 0Ch (FF)

\r carriage return, ASCII 0Dh (CR)

\e escape, ASCII 1Bh (ESC)

\s space, ASCII 20h (SPC)

\\ backslash, \

\nnn octal bit pattern, where nnn is 1-3 octal digits ([0-7])

\xnn hexadecimal bit pattern, where nn is 1-2 hexadecimal digits ([0-9a-fA-F])

\unnnn Unicode character, where nnnn is exactly 4 hexadecimal digits ([0-9a-fA-F])

\u{nnnn ...} Unicode character(s), where each nnnn is 1-6 hexadecimal digits ([0-9a-fA-F])

\cx or \C-x control character, where x is an ASCII printable character

\M-x meta character, where x is an ASCII printable character

\M-\C-x meta control character, where x is an ASCII printable character

\M-\cx same as above

\c\M-x same as above

\c? or \C-? delete, ASCII 7Fh (DEL)

Page 180: Ruby Keywords

Any other character followed by a backslash is interpreted as the character itself.

Double-quote strings allow interpolation of other values using #{...}:

"One plus one is two: #{1 + 1}"

Any expression may be placed inside the interpolated section, but it's best to keep

the expression small for readability.

Interpolation may be disabled by escaping the “#” character or using single-quote

strings:

'#{1 + 1}' #=> "\#{1 + 1}"

In addition to disabling interpolation, single-quoted strings also disable all escape sequences except for the single-quote (\') and backslash (\\).

You may also create strings using %:

%Q(1 + 1 is #{1 + 1}) #=> "1 + 1 is 2"

There are two different types of % strings %q(...) behaves like a single-quote string

(no interpolation or character escaping), while %Q behaves as a double-quote string.

See Percent Strings below for more discussion of the syntax of percent strings.

Adjacent string literals are automatically concatenated by the interpreter:

"con" "cat" "en" "at" "ion" #=> "concatenation" "This string contains " "no newlines." #=> "This string contains no newlines."

Any combination of adjacent single-quote, double-quote, percent strings will be

concatenated as long as a percent-string is not last.

%q{a} 'b' "c" #=> "abc" "a" 'b' %q{c} #=> NameError: uninitialized constant q

There is also a character literal notation to represent single character strings, which syntax is a question mark (?) followed by a single character or escape sequence that

corresponds to a single codepoint in the script encoding:

?a #=> "a"

?abc #=> SyntaxError

?\n #=> "\n"

?\s #=> " "

?\\ #=> "\\"

Page 181: Ruby Keywords

?\u{41} #=> "A"

?\C-a #=> "\x01"

?\M-a #=> "\xE1"

?\M-\C-a #=> "\x81"

?\C-\M-a #=> "\x81", same as above

?あ #=> "あ"

Here Documents

If you are writing a large block of text you may use a “here document” or “heredoc”:

expected_result = <<HEREDOC This would contain specially formatted text. That might span many lines HEREDOC

The heredoc starts on the line following <<HEREDOC and ends with the next line that

starts with HEREDOC. The result includes the ending newline.

You may use any identifier with a heredoc, but all-uppercase identifiers are typically

used.

You may indent the ending identifier if you place a “-” after <<:

expected_result = <<-INDENTED_HEREDOC This would contain specially formatted text. That might span many lines INDENTED_HEREDOC

Note that the while the closing identifier may be indented, the content is always

treated as if it is flush left. If you indent the content those spaces will appear in the

output.

To have indented content as well as an indented closing identifier, you can use a “squiggly” heredoc, which uses a “~” instead of a “-” after <<:

expected_result = <<~SQUIGGLY_HEREDOC This would contain specially formatted text. That might span many lines SQUIGGLY_HEREDOC

The indentation of the least-indented line will be removed from each line of the

content. Note that empty lines and lines consisting solely of literal tabs and spaces

Page 182: Ruby Keywords

will be ignored for the purposes of determining indentation, but escaped tabs and

spaces are considered non-indentation characters.

A heredoc allows interpolation and escaped characters. You may disable

interpolation and escaping by surrounding the opening identifier with single quotes:

expected_result = <<-'EXPECTED' One plus one is #{1 + 1} EXPECTED p expected_result # prints: "One plus one is \#{1 + 1}\n"

The identifier may also be surrounded with double quotes (which is the same as no

quotes) or with backticks. When surrounded by backticks the HEREDOC behaves

like Kernel#`:

puts <<-`HEREDOC` cat #{__FILE__} HEREDOC

To call a method on a heredoc place it after the opening identifier:

expected_result = "One plus one is #{1 + 1} ".chomp

You may open multiple heredocs on the same line, but this can be difficult to read:

puts("content for heredoc one ", "content for heredoc two ")

Symbols A Symbol represents a name inside the ruby interpreter. See Symbol for more details

on what symbols are and when ruby creates them internally. You may reference a symbol using a colon: :my_symbol.

You may also create symbols by interpolation:

:"my_symbol1" :"my_symbol#{1 + 1}"

Like strings, a single-quote may be used to disable interpolation:

:'my_symbol#{1 + 1}' #=> :"my_symbol\#{1 + 1}"

When creating a Hash, there is a special syntax for referencing a Symbol as well.

Page 183: Ruby Keywords

Arrays An array is created using the objects between [ and ]:

[1, 2, 3]

You may place expressions inside the array:

[1, 1 + 1, 1 + 2] [1, [1 + 1, [1 + 2]]]

See Array for the methods you may use with an array.

Hashes A hash is created using key-value pairs between { and }:

{ "a" => 1, "b" => 2 }

Both the key and value may be any object.

You can create a hash using symbol keys with the following syntax:

{ a: 1, b: 2 }

This same syntax is used for keyword arguments for a method.

Like Symbol literals, you can quote symbol keys.

{ "a 1": 1, "b #{1 + 1}": 2 }

is equal to

{ :"a 1" => 1, :"b 2" => 2 }

See Hash for the methods you may use with a hash.

Ranges A range represents an interval of values. The range may include or exclude its

ending value.

(1..2) # includes its ending value (1...2) # excludes its ending value

You may create a range of any object. See the Range documentation for details on

the methods you need to implement.

Page 184: Ruby Keywords

Regular Expressions A regular expression is created using “/”:

/my regular expression/

The regular expression may be followed by flags which adjust the matching behavior

of the regular expression. The “i” flag makes the regular expression case-insensitive:

/my regular expression/i

Interpolation may be used inside regular expressions along with escaped characters.

Note that a regular expression may require additional escaped characters than a

string.

See Regexp for a description of the syntax of regular expressions.

Procs A proc can be created with ->:

-> { 1 + 1 }

Calling the above proc will give a result of 2.

You can require arguments for the proc as follows:

->(v) { 1 + v }

This proc will add one to its argument.

Percent Strings Besides %(...) which creates a String, the % may create other types of object. As

with strings, an uppercase letter allows interpolation and escaped characters while a

lowercase letter disables them.

These are the types of percent strings in ruby:

%i

Array of Symbols

%q

String

%r

Regular Expression

%s

Symbol %w

Page 185: Ruby Keywords

Array of Strings

%x

Backtick (capture subshell result)

For the two array forms of percent string, if you wish to include a space in one of the

array entries you must escape it with a “\” character:

%w[one one-hundred\ one] #=> ["one", "one-hundred one"]

If you are using “(”, “[”, “{”, “<” you must close it with “)”, “]”, “}”, “>” respectively. You

may use most other non-alphanumeric characters for percent string delimiters such

as “%”, “|”, “^”, etc.

 

Page 186: Ruby Keywords

-end The end of a syntax block. Used by classes, modules, methods, exception

handling and control expressions.

-ensure Starts a section of code that is always run when an exception is raised.

See exception handling  

Exception Handling Exceptions are rescued in a begin/end block:

begin # code that might raise rescue # handle exception end

If you are inside a method, you do not need to use begin or end unless you wish to

limit the scope of rescued exceptions:

def my_method # ... rescue # ... end

The same is true for a class or module.

You can assign the exception to a local variable by using => variable_name at the

end of the rescue line:

begin # ... rescue => exception warn exception.message raise # re-raise the current exception end

By default, StandardError and its subclasses are rescued. You can rescue a specific set of exception classes (and their subclasses) by listing them after rescue:

begin # ... rescue ArgumentError, NameError # handle ArgumentError or NameError end

Page 187: Ruby Keywords

You may rescue different types of exceptions in different ways:

begin # ... rescue ArgumentError # handle ArgumentError rescue NameError # handle NameError rescue # handle any StandardError end

The exception is matched to the rescue section starting at the top, and matches only

once. If an ArgumentError is raised in the begin section, it will not be handled in

the StandardError section.

You may retry rescued exceptions:

begin # ... rescue # do something that may change the result of the begin block retry end

Execution will resume at the start of the begin block, so be careful not to create an

infinite loop.

Inside a rescue block is the only valid location for retry, all other uses will raise

a SyntaxError. If you wish to retry a block iteration use redo. See Control

Expressions for details. To always run some code whether an exception was raised or not, use ensure:

begin # ... rescue # ... ensure # this always runs end

You may also run some code when an exception is not raised:

begin # ... rescue # ... else # this runs only when no exception was raised ensure # ... end

Page 188: Ruby Keywords

class Exception Descendants of class Exception are used to communicate

between Kernel#raise and rescue statements in begin ... end blocks. Exception objects

carry information about the exception – its type (the exception's class name), an optional

descriptive string, and optional traceback information. Exception subclasses may add

additional information like NameError#name.

Programs may make subclasses of Exception, typically of StandardError or RuntimeError, to

provide custom classes and add additional information. See the subclass list below for

defaults for raise and rescue.

When an exception has been raised but not yet handled

(in rescue, ensure, at_exit and END blocks) the global variable $! will contain the current

exception and $@ contains the current exception's backtrace.

It is recommended that a library should have one subclass

of StandardError or RuntimeError and have specific exception types inherit from it. This

allows the user to rescue a generic exception type to catch all exceptions the library may raise

even if future versions of the library add new exception subclasses.

For example:

class MyLibrary class Error < RuntimeError end class WidgetError < Error end class FrobError < Error end end

To handle both WidgetError and FrobError the library user can rescue MyLibrary::Error.

The built-in subclasses of Exception are:

NoMemoryError

ScriptError

o LoadError

o NotImplementedError

o SyntaxError

SecurityError

SignalException

o Interrupt

StandardError – default for rescue

Page 189: Ruby Keywords

o ArgumentError

UncaughtThrowError

o EncodingError

o FiberError

o IOError

EOFError

o IndexError

KeyError

StopIteration

o LocalJumpError

o NameError

NoMethodError

o RangeError

FloatDomainError

o RegexpError

o RuntimeError – default for raise

o SystemCallError

Errno::*

o ThreadError

o TypeError

o ZeroDivisionError

SystemExit

SystemStackError

fatal – impossible to rescue

Exception serialization/deserialization

Public Class Methods

exception(string) → an_exception or exc

With no argument, or if the argument is the same as the receiver, return the receiver.

Otherwise, create a new exception object of the same class as the receiver, but with a message

equal to string.to_str. json_create(object)

Deserializes JSON string by constructing new Exception object with message m and

backtrace b serialized with to_json new(msg = nil) → exception

Construct a new Exception object, optionally passing in a message.

Page 190: Ruby Keywords

Public Instance Methods

exc == obj → true or false

Equality—If obj is not an Exception, returns false. Otherwise,

returns true if exc and obj share same class, messages, and backtrace. as_json(*)

Returns a hash, that will be turned into a JSON object and represent this object. backtrace → array

Returns any backtrace associated with the exception. The backtrace is an array of strings, each

containing either “filename:lineNo: in `method''' or “filename:lineNo.''

def a raise "boom" end def b a() end begin b() rescue => detail print detail.backtrace.join("\n") end

produces:

prog.rb:2:in `a'

prog.rb:6:in `b'

prog.rb:10

backtrace_locations → array

Returns any backtrace associated with the exception. This method is similar to #backtrace, but

the backtrace is an array of

Thread::Backtrace::Location.

Now, this method is not affected by #set_backtrace. cause → an_exception or nil

Returns the previous exception ($!) at the time this exception was raised. This is useful for

wrapping exceptions and retaining the original exception information.

Page 191: Ruby Keywords

exception(string) → an_exception or exc

With no argument, or if the argument is the same as the receiver, return the receiver.

Otherwise, create a new exception object of the same class as the receiver, but with a message

equal to string.to_str. inspect → string

Return this exception's class name and message

message → string

Returns the result of invoking exception.to_s. Normally this returns the exception's

message or name. By supplying a to_str method, exceptions are agreeing to be used where

Strings are expected. set_backtrace(backtrace) → array

Sets the backtrace information associated with exc. The backtrace must be an array of String

objects or a single String in the format described in #backtrace. to_json(*args)

Stores class name (Exception) with message m and backtrace array b as JSON string to_s → string

Returns exception's message (or the name of the exception if no message is set).

 

Page 192: Ruby Keywords

-elsif An alternate condition for an if expression. See control expressions

 

Control Expressions Ruby has a variety of ways to control execution. All the expressions described here

return a value.

For the tests in these control expressions, nil and false are false-values

and true and any other object are true-values. In this document “true” will mean

“true-value” and “false” will mean “false-value”.

if Expression The simplest if expression has two parts, a “test” expression and a “then”

expression. If the “test” expression evaluates to a true then the “then” expression is

evaluated.

Here is a simple if statement:

if true then puts "the test resulted in a true-value" end

This will print “the test resulted in a true-value”.

The then is optional:

if true puts "the test resulted in a true-value" end

This document will omit the optional then for all expressions as that is the most

common usage of if.

You may also add an else expression. If the test does not evaluate to true

the else expression will be executed:

if false puts "the test resulted in a true-value" else puts "the test resulted in a false-value" end

This will print “the test resulted in a false-value”.

You may add an arbitrary number of extra tests to an if expression using elsif.

An elsif executes when all tests above the elsif are false.

Page 193: Ruby Keywords

a = 1 if a == 0 puts "a is zero" elsif a == 1 puts "a is one" else puts "a is some other value" end

This will print “a is one” as 1 is not equal to 0. Since else is only executed when there

are no matching conditions. Once a condition matches, either the if condition or any elsif condition,

the if expression is complete and no further tests will be performed.

Like an if, an elsif condition may be followed by a then.

In this example only “a is one” is printed:

a = 1 if a == 0 puts "a is zero" elsif a == 1 puts "a is one" elsif a >= 1 puts "a is greater than or equal to one" else puts "a is some other value" end

The tests for if and elsif may have side-effects. The most common use of side-

effect is to cache a value into a local variable:

if a = object.some_value # do something to a end

The result value of an if expression is the last value executed in the expression.

Ternary if You may also write a if-then-else expression using ? and :. This ternary if:

input_type = gets =~ /hello/i ? "greeting" : "other"

Is the same as this if expression:

input_type = if gets =~ /hello/i "greeting" else "other" end

Page 194: Ruby Keywords

While the ternary if is much shorter to write than the more verbose form, for

readability it is recommended that the ternary if is only used for simple conditionals.

Also, avoid using multiple ternary conditions in the same expression as this can be

confusing.

unless Expression The unless expression is the opposite of the if expression. If the value is false, the

“then” expression is executed:

unless true puts "the value is a false-value" end

This prints nothing as true is not a false-value.

You may use an optional then with unless just like if.

Note that the above unless expression is the same as:

if not true puts "the value is a false-value" end

Like an if expression you may use an else condition with unless:

unless true puts "the value is false" else puts "the value is true" end

This prints “the value is true” from the else condition.

You may not use elsif with an unless expression.

The result value of an unless expression is the last value executed in the expression.

Modifier if and unless if and unless can also be used to modify an expression. When used as a modifier

the left-hand side is the “then” expression and the right-hand side is the “test”

expression:

a = 0 a += 1 if a.zero? p a

Page 195: Ruby Keywords

This will print 1.

a = 0 a += 1 unless a.zero? p a

This will print 0.

While the modifier and standard versions have both a “test” expression and a “then”

expression, they are not exact transformations of each other due to parse order. Here

is an example that shows the difference:

p a if a = 0.zero?

This raises the NameError “undefined local variable or method `a'”. When ruby parses this expression it first encounters a as a method call in the “then”

expression, then later it sees the assignment to a in the “test” expression and

marks a as a local variable.

When running this line it first executes the “test” expression, a = 0.zero?.

Since the test is true it executes the “then” expression, p a. Since the a in the body

was recorded as a method which does not exist the NameError is raised. The same is true for unless.

case Expression The case expression can be used in two ways.

The most common way is to compare an object against multiple patterns. The

patterns are matched using the +===+ method which is aliased to +==+ on Object.

Other classes must override it to give meaningful behavior.

SeeModule#=== and Regexp#=== for examples. Here is an example of using case to compare a String against a pattern:

case "12345" when /^1/ puts "the string starts with one" else puts "I don't know what the string starts with" end

Here the string "12345" is compared with /^1/ by calling /^1/ === "12345" which

returns true. Like the if expression, the first when that matches is executed and all

other matches are ignored. If no matches are found, the else is executed.

Page 196: Ruby Keywords

The else and then are optional, this case expression gives the same result as the

one above:

case "12345" when /^1/ puts "the string starts with one" end

You may place multiple conditions on the same when:

case "2" when /^1/, "2" puts "the string starts with one or is '2'" end

Ruby will try each condition in turn, so first /^1/ === "2" returns false, then "2" ===

"2" returns true, so “the string starts with one or is '2'” is printed.

You may use then after the when condition. This is most frequently used to place the

body of the when on a single line.

case a

when 1, 2 then puts "a is one or two

when 3 then puts "a is three"

else puts "I don't know what a is"

end

The other way to use a case expression is like an if-elsif expression:

a = 2 case when a == 1, a == 2 puts "a is one or two" when a == 3 puts "a is three" else puts "I don't know what a is" end

Again, the then and else are optional.

The result value of a case expression is the last value executed in the expression.

Page 197: Ruby Keywords

while Loop The while loop executes while a condition is true:

a = 0 while a < 10 do p a a += 1 end p a

Prints the numbers 0 through 10. The condition a < 10 is checked before the loop is

entered, then the body executes, then the condition is checked again. When the

condition results in false the loop is terminated. The do keyword is optional. The following loop is equivalent to the loop above:

while a < 10 p a a += 1 end

The result of a while loop is nil unless break is used to supply a value.

until Loop The until loop executes while a condition is false:

a = 0 until a > 10 do p a a += 1 end p a

This prints the numbers 0 through 11. Like a while loop the condition a > 10 is

checked when entering the loop and each time the loop body executes. If the

condition is false the loop will continue to execute. Like a while loop, the do is optional.

Like a while loop, the result of an until loop is nil unless break is used.

Page 198: Ruby Keywords

for Loop The for loop consists of for followed by a variable to contain the iteration argument

followed by in and the value to iterate over using each. The do is optional:

for value in [1, 2, 3] do puts value end

Prints 1, 2 and 3.

Like while and until, the do is optional.

The for loop is similar to using each, but does not create a new variable scope.

The result value of a for loop is the value iterated over unless break is used.

The for loop is rarely used in modern ruby programs.

Modifier while and until Like if and unless, while and until can be used as modifiers:

a = 0 a += 1 while a < 10 p a # prints 10

until used as a modifier:

a = 0 a += 1 until a > 10 p a # prints 11

You can use begin and end to create a while loop that runs the body once before the

condition:

a = 0 begin a += 1 end while a < 10 p a # prints 10

If you don't use rescue or ensure, Ruby optimizes away any exception handling

overhead.

Page 199: Ruby Keywords

break Statement Use break to leave a block early. This will stop iterating over the items in values if

one of them is even:

values.each do |value| break if value.even? # ... end

You can also terminate from a while loop using break:

a = 0 while true do p a a += 1 break if a < 10 end p a

This prints the numbers 0 and 1.

break accepts a value that supplies the result of the expression it is “breaking” out of:

result = [1, 2, 3].each do |value| break value * 2 if value.even? end p result # prints 4

next Statement Use next to skip the rest of the current iteration:

result = [1, 2, 3].map do |value| next if value.even? value * 2 end p result # prints [2, nil, 6]

Page 200: Ruby Keywords

next accepts an argument that can be used the result of the current block iteration:

result = [1, 2, 3].map do |value| next value if value.even? value * 2 end p result # prints [2, 2, 6]

redo Statement Use redo to redo the current iteration:

result = [] while result.length < 10 do result << result.length redo if result.last.even? result << result.length + 1 end p result

This prints [0, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]

In Ruby 1.8, you could also use retry where you used redo. This is no longer true,

now you will receive a SyntaxError when you use retry outside of a rescue block.

See Exceptions for proper usage of retry.

Flip-Flop The flip-flop is a rarely seen conditional expression. It's primary use is for processing text from ruby one-line programs used with ruby -n or ruby -p.

The form of the flip-flop is an expression that indicates when the flip-flop turns on, .. (or ...), then an expression that indicates when the flip-flop will turn off. While

the flip-flop is on it will continue to evaluate to true, andfalse when off.

Here is an example:

selected = [] 0.upto 10 do |value| selected << value if value==2..value==8 end p selected # prints [2, 3, 4, 5, 6, 7, 8]

Page 201: Ruby Keywords

In the above example, the on condition is n==2. The flip-flop is initially off (false) for 0

and 1, but becomes on (true) for 2 and remains on through 8. After 8 it turns off and

remains off for 9 and 10. The flip-flop must be used inside a conditional such as if, while, unless, until etc.

including the modifier forms. When you use an inclusive range (..), the off condition is evaluated when the on

condition changes:

selected = [] 0.upto 5 do |value| selected << value if value==2..value==2 end p selected # prints [2]

Here, both sides of the flip-flop are evaluated so the flip-flop turns on and off only when value equals 2. Since the flip-flop turned on in the iteration it returns true.

When you use an exclusive range (...), the off condition is evaluated on the

following iteration:

selected = [] 0.upto 5 do |value| selected << value if value==2...value==2 end p selected # prints [2, 3, 4, 5]

Here, the flip-flop turns on when value equals 2, but doesn't turn off on the same

iteration. The off condition isn't evaluated until the following iteration and value will

never be two again.