Professional Documents
Culture Documents
Contents
z RGSS Specifications
z Ruby Syntax
{ Syntax and Expressions
{ Variables and Constants
{ Literals
{ Operator Expressions
{ Control Structures
{ Method Calls
{ Class and Method Definitions
z Standard Library
{ Built-in Functions
{ Built-in Variables
{ Built-in Classes
{ Built-in Modules
{ Built-in Exception Classes
z Game Library
{ RGSS Built-in Functions
{ RGSS Built-in Classes
{ RGSS Built-in Modules
{ RPGVX Data Structure
z Appendix
{ Regular Expressions
{ sprintf Format
This document presents a selection of entries from the Ruby reference manual, the bare minimum needed for using
RGSS. It has been edited to include explanations of RGSS's unique specifications as well. Aimed at RGSS users, we've
greatly scaled back on those areas that aren't important for game programming and updated each entry. This means
that some portions might not be strictly accurate; as a Ruby reference, it's no more than a quick-and-dirty guide and
should be treated as such.
The original Ruby language, as well as the source for this document, can be found at the official Ruby homepage:
http://www.ruby-lang.org/. Check it out if you need more detailed Ruby information.
User Support
Enterbrain provides no user support for creating games with the script editor or any problems that may arise from the
game-creation process. Furthermore, neither Enterbrain nor Yukihiro Matsumoto assume any responsibility to provide
Ruby script support. Be sure you have a thorough understanding of RGSS's functions when attempting to edit a script.
Be a responsible programmer--make sure to check these pages, the Ruby homepage, any other Ruby information and
support sites, and similar resources before approaching a site administrator for assistance.
RGSS Specifications
z Differences from the Previous Version
z Starting a Game
z Game.ini
z RGSS-RTP
{ Installation Data
z Encrypted Archives
z Other
{ Character Set
{ Frame Rate
{ Properties
RGSS2, which is incorporated into RPG Maker VX, has a number of differences from RGSS1, which was included with
RPG Maker XP. The main differences are listed below.
z The default resolution has been changed from 640×480 to 544×416 and the default frame rate has been changed
from 40 to 60. Smooth Mode has been removed.
z Double buffering is now used for drawing in Full Screen mode. If your computer meets the recommended
specifications, scrolling should be very smooth.
z The function that would assume that the program had hung up if the screen had not been refreshed for a long
period of time and automatically perform a force quit has been removed. Even if the screen is not refreshed,
Windows messages will still be processed normally, so in most cases you can force quit by using Alt+F4 as usual.
z It is now possible to easily perform a fade-in or fade-out of the screen. To do this, you use the Graphics.fadeout
and Graphics.fadein methods.
z It is now possible to get a bitmap image of the current game screen. To do this, you use the
Graphics.snap_to_bitmap method.
z The tilemap (Tilemap) class has been significantly changed to match the RPGVX map specifications.
z It is now possible to use effects such as Blur or Radial Blur with bitmaps (Bitmap).
z For sprites (Sprite), a wave effect (similar to a raster scroll effect) is now supported.
z By placing font files in the Fonts folder inside the game folder, it is now possible to directly use fonts that are not
installed on the system.
z Shadow text is now supported for the Font class (Font). A number of the default values were also changed.
z It is now possible to change viewport (Viewport) associations after the fact. Sprites and other elements associated
with viewports will no longer be automatically freed.
z The timing with which the BGM restarts after ME playback has been improved (Audio.me_play).
In addition to the above, a number of other minor changes have been made.
In this manual, functions or specifications that have been changed for RGSS2 will be marked with a (RGSS2) symbol.
Starting a Game
Normally, you launch RGSS by double-clicking the icon for the game file, Game.exe (or Game if the Game
Windows option "Hide extensions for known file types" has been turned on). The folder that contains
this file is called the game folder.
In-progress games can be started up by selecting [Playtest] from the menu or [Battle Test] from the Troop database.
When this is done, the global variable $TEST will be set to true. When performing a Battle Test, the $BTEST variable
will also be set to true. With RGSS1, the value of the Ruby built-in variable $DEBUG was changed but this was removed
because differences in behavior could lead to problems in rare cases. (RGSS2)
Game.ini
The Game.ini file is automatically created and updated by RPGVX. It can also be edited manually with Notepad or
another text editor.
Example:
[Game]
RTP=RPGVX
Library=RGSS200E.dll
Scripts=Data\Scripts.rvdata
Title=RubyQuest
RTP
Library
The name of the RGSS DLL. This file is usually installed in the RTP folder.
Scripts
The data file in which scripts are stored, specified with a path relative to the game folder.
Ruby's scripts usually take the form of text files with the extension .rb, but RGSS uses one proprietary packaged
file. This file cannot usually be edited without using RPGVX's script editor. The data is comprised of multiple
sections and is executed in the listed order, as displayed.
Title
RGSS-RTP
RTP (Run-Time Package) is a mechanism that reduces game data size for distribution. RTP contains standard graphics
and audio files used across many different games. Installing these resources as a common file before playing a game
eliminates the need to download duplicate files over and over.
RTP files can use the following methods from the built-in game library to access files as though they were in the game
folder. The extensions can be left off the file names that are passed to the methods below--their file types (such as .png
or .mid) are identified automatically.
Installation Data
The standard RTP for RPG Maker VX is just "RPGVX" but it is now possible to use RTPs with different structures. If you
know how to make an installer, follow these steps to create a unique RTP at the user level. However, using common
names for RTP titles, such as "Extension", is not recommended; they might conflict with the names of new, official RTPs
in the future.
[CommonFilesFolder]\Enterbrain\RGSS2\[RTPName]
Here, [CommonFilesFolder] is the location of the Windows "Common Files" folder, while [RTPName] is the name of the
RTP. Here's an example:
The RTP installer creates a string value containing the RTP name in the
"HKEY_LOCAL_MACHINE\SOFTWARE\Enterbrain\RGSS2\RTP" registry key and uses it to set the path. RGSS
recognizes the string specified in this key as the RTP. (RGSS2)
Encrypted Archives
Encrypted archives make it difficult for others to analyze and/or rebuild the game contents. Normally all data and graphic
files (not audio and font files) are stored in Game.rgss2a. You can create an encrypted archive by checking the [Create
encrypted archive] box when compressing the game data.
The files within the encrypted archive can use the following methods from the built-in game library to access files as
though they were in the game folder:
When there is an encrypted archive in the game folder, the script data (normally Data\Scripts.rvdata) defined in the
Scripts line of Game.ini will always be read from the archive. This is a limitation that prevents files within the archive
from being read by an external script.
Due to its nature, the encrypted archive's internal format has not, and will not, been released to the public. Please
refrain from analyzing it.
Other
Character Set
RGSS uses the UTF-8 character set. UTF-8 is a way of encoding Unicode, a character set that can display letters and
characters from all the world's languages.
Ruby's built-in variable $KCODE (not included in this reference) is set to "UTF8" by default. RPGVX's script data and all
other string data are also in UTF-8, so you don't have to worry about any encoding conflicts as you build your game.
Frame Rate
The standard frame rate for RGSS2 games is 60 frames per second. With RGSS1, it was possible to turn the Smooth
Mode option off and skip drawing some frames, thereby making games run at half frame rate, but this has been
eliminated with RGSS2.(RGSS2)
Properties
The term "property" is used in the game library overview. This is not a concept in Ruby's specifications, but rather a term
unique to RGSS.
For example, this is how to obtain and set a sprite's x-coordinate (Sprite#x):
x = sprite1.x # obtain
sprite2.x = x + 32 # set
For the sake of convenience, methods that are defined to both obtain (read) and set (write) via assignment operators in
this way are called "properties".
When objects such as the Color class, the Tone class, or the Rect class are defined as properties, a reference to the
object itself is returned to the caller, rather than a copy. Therefore, it is possible to change the color of a font by using
this format:
color = font1.color
color.set(255, 0, 0)
Ruby Syntax
z Syntax and Expressions
{ Identifiers
{ Comments
{ Reserved Words
{ Expressions
z Variables and Constants
{ Local Variables
{ Instance Variables
{ Class Variables
{ Global Variables
{ Constants
{ Pseudo Variables
z Literals
{ Number Literals
{ String Literals
Backslash Notation
Formula Development
{ Array Expressions
{ Hash Expressions
{ Range Expressions
{ Symbols
z Operational Forms
{ Assignment
Self-assignment
Multiple Assignment
{ and
{ or
{ not
{ Conditional Operators
z Control Structures
{ Conditional Branching
if
if Modifier
unless
unless Modifier
case
{ Looping
while
while Modifier
until
until Modifier
for
break
next
{ Exception Handling
raise
begin
rescue Modifiers
{ Method Ending
return
z Calling Methods
{ super
{ Iterators
{ yield
z Defining Classes and Methods
{ Class Definition
{ Module Definition
{ Method Definition
Method Evaluation
Ruby is a case-sensitive language. Apart from within identifiers and some literals, blank space and comments may
be placed anywhere as needed. Line breaks are treated as blank space only when used to clearly show a line is
continuing; otherwise, they are treated as phrase delimiters.
Identifiers
Example:
foobar
ruby_is_simple
An identifier in Ruby begins with an alphabetic character or underscore (_) and consists of alphanumeric
characters or underscores (_). There is no limit on length.
Comments
Example:
Reserved Words
Reserved words cannot be used for names of classes, variables, or the like. However, words prefixed by $ or @
are not considered reserved. Furthermore, these words can be used as method names after def, after a method-
call period, and in other cases where it is clear that the word is acting as a method name.
Expressions
Example
true
(1+2)*3
foo()
if test then ok else ng end
The term "expressions" encompasses everything from variables and literals to operational forms and control
structures.
A collection of these expressions makes up a Ruby program. Expressions are separated from one another with
semicolons (;) or line breaks. However, a line break following a backslash is not considered a new expression
boundary; instead, the expression continues on the next line.
The type of variable or constant in Ruby--local variables, instance variables, class variables, global variables, and
constants--can be determined from its initial character. Normally a variable has an alphanumeric name (outside of
its first character) which can include an underscore, but some built-in variables begin with '$' + one character (see
Built-In Variables).
Variables and constants point to specified objects. Assigning objects to variables and constants simply makes
them point to new objects; it does not create new copies of objects.
Local Variables
Example:
foobar
Identifiers beginning with a lowercase letter or '_' are local variables or method calls.
Within a local variable's scope (classes, modules, method definitions), the initial assignment to an identifier
beginning with lowercase letters is the declaration of that scope's local variable. Referencing undeclared identifiers
is considered a call to a method with no arguments.
Instance Variables
Example:
@foobar
Variables beginning with '@' are instance variables and belong to specific objects. Instance variables can be
referenced from any method of their class or subclass. When referenced, the value of an uninitialized instance
variable is nil.
Class Variables
Example:
class Foo
@@foo = 1
def bar
puts @@foo
end
end
Variables beginning with @@ are class variables. Class variables are defined within the class definition and can be
referenced/assigned from class-unique methods, instance methods, etc.
Global Variables
Example:
$foobar
Variables beginning with '$' are global variables and can be referenced from anywhere in the program (thus
requiring some caution when using). Global variables do not need declarations. When referenced, the value of an
uninitialized global variable is nil.
Pseudo Variables
Apart from the usual variables, there are also special variables known as pseudo variables.
self
nil
true
false
The value of a pseudo variable cannot be changed. Assigning values to pseudo variables will result in a syntax
error.
Constants
Example:
FOOBAR
Identifiers beginning with an uppercase letter are constants. The definition of a constant (and its initialization)
depends on its assignment; constants cannot be defined with a method. Accessing an undefined constant throws
a NameError exception.
Within the class or module in which a constant is defined, the constant can be referenced by inheriting classes,
classes that include modules, and modules. To reference constants externally, use the '::' operator.
class Foo
FOO = 'FOO'
end
Literals
{ Numeric Literals
{ String Literals
Backslash Notation
Expression Substitution
{ Regular Expressions
{ Array Expressions
{ Hash Expressions
{ Range Expressions
{ Symbols
Values that can be expressed directly in Ruby programs, such as the number 1 or the string "hello world", are
called literals.
Numeric Literals
123
0d123
integer
-123
integer (signed)
123.45
Floating point numbers beginning with a decimal point, like .1, are not allowed. They must be written with a
leading zero (0.1).
1.2e-3
0xffff
hexadecimal integer
0b1011
binary integer
0377
0o377
octal integer
Numeric literals can contain an underscore. The Ruby interpreter simply ignores these underscores and does not
interpret them in a special way. This can be useful as a thousands separator for large values. However, placing an
underscore before and after a literal or connecting literals with an underscore will result in an error.
String Literals
Example:
String expressions begin and end with double or single quote marks.
Double-quoted string expressions are subject to backslash notation and expression substitution. Single-quoted
strings are not (except for \' and \\).
String literals with white space on either side are treated as a single string literal.
Backslash Notation
\t
tab (0x09)
\n
newline (0x0a)
\r
\f
\s
whitespace (0x20)
\nnn
\xnn
Expression Substitution
In double-quoted strings and regular expressions, the form "#{expression}" can be extended to the (string of the)
contents of that expression. If the expressions are variables beginning with either $ or @, the surrounding braces
may be omitted and the variable can be expressed as a #variable. The character # is interpreted literally if it is not
followed by the characters {, $, or @. To explicitly prevent expression substitution, place a backslash in front of the
#.
$ruby = "RUBY"
p "my name is #{$ruby}" # => "my name is RUBY"
p 'my name is #{$ruby}' # => "my name is #{$ruby}"
Regular Expressions
Example:
Strings delimited by slashes are regular expressions, which are instances of the Regexp class.
Refer to Regular Expressions for more information on which metacharacters are interpreted as regular
expressions.
The characters immediately following the final slash denotes a regular expression option:
Multiple run mode. Newlines are treated as normal characters (matching with the . character).
Ruby correctly handles multibyte characters (such as Chinese and Japanese) in regular expressions.
Backslash notation and expression substitution are available in regular expressions, as in strings.
If a regular expression does not include expression substitution, it will return the same regular expression object
every time it is evaluated. If expression substitution is included, the regular expression will be compiled with every
evaluation (based on the expression substitution results) and a new regular expression object will be created.
Array Expressions
Example:
[1, 2, 3]
Syntax:
Returns an array containing the result of each expression. Arrays are instances of the class Array.
Array expressions spawn a new array object every time they are evaluated.
Hash Expressions
Example:
Syntax:
Returns a new hash object that maps each resulting value to a key. Hashes are instances of the class Hash.
A hash (also called an associative array) can associate one object of an arbitrary type with another.
Hash expressions spawn a new hash object every time they are evaluated.
Range Expressions
Example:
1 .. 20
Syntax:
If a range expression appears anywhere but a conditional expression, returns the range object from expression 1
to expression 2. Range objects are instances of the class Range.
Range objects spawned by .. operators include the final expression, while those spawned by ... operators do not.
If both ends of a range expression are numeric literals, the expression will return the same object every time it is
evaluated. Otherwise, the expression will return a new range object every time it is evaluated.
Symbols
Example:
:class
:lvar
:method
:$gvar
:@ivar
:+
Syntax:
':' identifier
':' variable name
':' operator
Returns symbols that have a one-to-one correspondence with arbitrary strings. Symbols are an instance of the
Symbol class.
Symbols are unique objects that return the same object every time they are evaluated.
Operator Expressions
{ Assignment
Self-Assignment
Multiple Assignment
{ and
{ or
{ not
{ Conditional Operators
Example:
1+2*3/4
Some method calls and control structures take the form of operators for ease in programming. Ruby contains the
following operators:
high ::
[]
**
-(unary) +(unary) ! ~
* / %
+ -
<< >>
&
| ^
> >= < <=
<=> == === != =~ !~
&&
||
.. ...
?:(conditional operator)
=(+=, -= ... )
not
low and or
"High" and "low" signify the operators' priority level. For example, "&&" has a higher priority than "||", so it would be
interpreted in the following way:
Most operators are method calls in special form, but some are built into the language and cannot be redefined.
+@ and -@ represent the unary operators + and -. This notation is used in method definitions and the like.
Combination operators (i.e., self-assignment operators, !=, and !~) cannot be redefined.
Assignment
Example:
foo = bar
foo[0] = bar
foo.bar = baz
Syntax:
Assignment expressions are used to assign values to variables and the like. Assignments can also be used as
declarations for local variables or constants. The left side of an assignment expression must be one of the
following:
{ a variable
If there is a variable on the left side, the value of the expression is assigned to the variable.
{ an array reference
For the object obtained by evaluating expr1, this form is converted into a []= method call with expr2 through
exprN as arguments.
class C
def initialize
@ary = [0,1,2,3,4,5,6,7]
end
def [](i)
@ary[i * 2]
end
def []=( i, v )
@ary[i * 2] = v
end
end
c = C.new
p c[3] # converted to c.[]( 3 ); result is 6
p c[3] = 1 # converted to c.[]=(3,1); result is 1
{ an attribute reference
For the object obtained by evaluating expr1, calls the identifier= method with expr2 as an argument.
class C
def foo
@foo
end
def foo=( v )
@foo = v
end
end
c = C.new
c.foo = 5 # converted to c.foo=( 5 )
p c.foo # => 5
class C
attr_accessor :foo
end
c = C.new
c.foo = 5 # converted to c.foo=( 5 )
p c.foo # => 5
Self-Assignment
Example:
Syntax:
op is one of the following. There can be no space between the operator and =.
Multiple Assignment
Example:
Syntax:
expr [',' [ expr ',' ... ] ['*' [ expr ]]] = expr [, expr ... ]['*' expr ]
'*' [ expr ] = expr [, expr ... ]['*' expr ]
Multiple assignment performs assignments from multiple expressions or arrays. Each expression on the left must
be assignable. If there is only one expression on the right, its value will be converted into an array whose elements
will be assigned to the expressions on the left. If there are more elements in the array than on the left, the extra
elements are ignored. If there are too few elements in the array, nil will be assigned to the extra elements on the
left.
Prepend * to the final expression on the left to assign all extra lefthand elements to that expression as an array. If
there are no extra elements, an empty array will be assigned.
and
Example:
Syntax:
First evaluates the left side; if the result is true, evaluates the right side. and does the same as &&, but is a lower
priority operator.
or
Example:
demo || die
demo or die
Syntax:
First evaluates the left side; if the result is false, evaluates the right side. or does the same as ||, but is a lower
priority operator.
not
Example:
! me
not me
i != you
Syntax:
'!' expr
not expr
If the value of the expression is true, returns FALSE; if the value is false, returns TRUE.
Conditional Operators
Example:
Syntax:
Returns expr2 or expr3 depending on the results of expr1. This is identical to:
Control Structures
{ Conditional Branching
if
if Modifier
unless
unless Modifier
case
{ Looping
while
while Modifier
until
until Modifier
for
break
next
{ Exception Handling
raise
begin
rescue Modifier
{ Method Exit
return
Unlike in C, control structures in Ruby are expressions that return some value.
Ruby carries over some control structures from C and Perl, but also features a loop abstraction feature called
iterators. Iterators are user-definable looping control structures.
Conditional Branching
if
Examples:
Syntax:
if expr [then]
expr ...
[elsif expr [then]
expr ... ]
...
[else
expr ... ]
end
If a conditional expression is evaluated as true, evaluates the expression beginning with then. If the if expression
is false, evaluates the elsif condition. Multiple elsif clauses can be specified; when all if or elsif conditional
expressions are false, the else clause expression, if any, is evaluated.
if returns the value of the last evaluated expression in the conditional expression clause (or else clause). If there is
no else clause and no conditional expressions in effect, returns nil.
The values false and nil are false; everything else, including zero and empty text strings, is true.
Note that Ruby uses elsif after if, not else if and not elif.
if Modifier
Example:
Syntax:
expr if expr
Evaluates and returns the result of the expression on the left if the condition on the right is true. If the condition is
unless
Example:
unless baby?
feed_meat
else
feed_milk
end
Syntax:
unless is the reverse of if; if the conditional expression is false, evaluates the expression beginning with then. elsif
cannot be specified with unless.
unless Modifier
Example:
Syntax:
Evaluates and returns the result of the expression on the left if the condition on the right is false. If the condition is
not in effect, returns nil.
case
Example:
case $age
when 0 .. 2
"baby"
when 3 .. 6
"little child"
when 7 .. 12
"child"
when 13 .. 18
"youth"
else
"adult"
end
Syntax:
case expr
[when expr [, expr] ... [then]
expr ..]..
[else
expr ..]
end
case expressions execute branching for a single expression via matching. Comparisons of values specified in a
when clause to the evaluated result of the first expression are performed by the === operator. When the values
match, evaluates the contents of the when clause.
case returns the result of the last evaluated expression in a conditional when (or else) clause. If neither condition
is in effect, returns nil.
Looping
while
Example:
ary = [0,2,4,8,16,32,64,128,256,512,1024]
i = 0
while i < ary.length
print ary[i]
i += 1
end
Syntax:
while returns nil. Alternatively, the while return value can also be the value of an argument to a break.
while Modifier
Example:
Syntax:
Repeatedly executes the expression on the left as long as the expression on the right is evaluated as true. If the
expression on the left is begin, while evaluates it first before looping.
The while modifier returns nil. Alternatively, the while modifier return value can also be the value of an argument to
a break.
until
Example:
until f.eof?
print f.gets
end
Syntax:
...
end
until returns nil. Alternatively, the until return value can also be the value of an argument to a break.
until Modifier
Example:
Syntax:
Repeatedly executes the expression on the left until the expression on the right is evaluated as true. If the
expression on the left is begin, the until modifier evaluates it first before looping.
The until modifier returns nil. Alternatively, the until modifier return value can also be the value of an argument to a
break.
for
Example:
for i in [1, 2, 3]
print i*2, "\n"
end
Syntax:
Repeatedly executes the contents for each evaluated object element. Approximately identical to the following:
It is only approximately identical because while blocks defined by do ... end or by { } introduce a new block scope
for local variables, for has no effect on the scope of local variables.
for returns the return value of the each method for the objects specified in in.
break
Example:
i = 0
while i < 3
print i, "\n"
break
end
Syntax:
break [expr]
break escapes from the innermost loop. A "loop" is one of the following:
{ while
{ until
{ for
{ an iterator
Unlike in C, break can only escape from loops. It does not exit from case.
for or an iterator that has escaped from a loop via break returns nil. However, if an argument is specified, the
loop's return value will become that argument.
next
Example:
str.each_line do |line|
next if line.empty?
print line
end
Syntax:
next [expr]
next jumps to the next iteration of the innermost loop. In an iterator, next is an escape for a yield call.
A yield that has escaped via next returns nil. However, if an argument is specified, yield's return value will become
that argument.
Exception Handling
raise
Examples:
raise
raise "you lose"
raise SyntaxError.new("invalid syntax")
raise SyntaxError, "invalid syntax"
Syntax:
raise
raise message
raise exception
raise error_type, message
Throws an exception. In the first format, throws the last exception again. In the second format, given a string
argument, throws a RuntimeError exception with the given string as a message. In the third format, throws the
exception if the argument is an exception object. In the last format, throws the exception specified in the first
argument with the message given in the second argument.
begin
Example:
begin
do_something
rescue
recover
ensure
must_do
end
Syntax::
begin
expr ..
[rescue [error_type,..] [then]
expr ..]..
[ensure
expr ..]
end
If an exception is thrown while begin is being executed, a rescue clause can trap the exception; multiple clauses
can be specified. If a rescue clause with a matching exception type exists, it is executed. The thrown exception
can be referenced with the built-in variable $!.
When error_type is omitted, it traps all exceptions in the StandardError subclasses, of which most built-in
exceptions in Ruby are members. See Built-in Exception Classes.
In rescue clauses, error_type is evaluated in the same way as an argument. If any value matches, the clause will
be executed. If the value of error_type is not a class or a module, rescue throws a TypeError exception.
If there is an ensure clause, its contents are always evaluated immediately before a begin expression exits.
begin returns the result of the final argument evaluated in either its contents or in the rescue clause.
rescue Modifier
Example:
Syntax:
When an exception is thrown in the first expression, evaluates the second expression. You cannot specify the
exception class(es) to be trapped; in other words, you can only trap the subclasses of the StandardError exception
class.
Expressions associated with the rescue modifier return expr1 if no exception is thrown and expr2 if an exception is
thrown.
Method Exit
return
Example:
return
return 12
return 1,2,3
Syntax:
Exits from a method with the return value. If two or more expressions are provided, the method's return value will
consist of an array containing these values. If the expression is omitted, the return value will be nil.
Method Calls
{ super
{ Iterators
{ yield
Example:
foo.bar()
foo.bar
bar()
print "hello world\n"
print
Syntax:
Method calls invoke the method of the receiver (the value of the expression to the left of the dot). If no receiver is
specified, calls the method of self.
Method names can be normal identifiers or identifiers followed by the character ? or !. Customarily, ? is used for
predicates (methods returning true/false values), while ! is used for methods that are more destructive than their !-
less counterparts (tr versus tr!).
If the last argument is preceded by *, the value of that expression is expanded to its arguments:
super
Example:
super
super(1,2,3)
Syntax:
super
super(expr , ... )
super calls the method that is being overridden by the current method. If the parentheses and arguments are
omitted, the current method's arguments are passed to super as is. To call the overridden method without passing
any arguments, indicate the parentheses as in super().
class Foo
def foo(arg=nil)
p arg
end
end
Iterators
Example:
Syntax:
method(arg1, arg2, ...) do ['|' expr ... '|'] expr ... end
method(arg1, arg2, ...) '{' ['|' expr ... '|'] expr ... '}'
Iterators are methods used for abstracting control structures (especially loops). If you call a method that is followed
by a code segment enclosed by do ... end or by { ... } (called a block), the method can evaluate the block from
within. Methods that call these kinds of blocks are called iterators. Block calls from iterators use yield. The value
passed to yield is assigned to the variable between the two pipes ( | ).
Local variables that are first assigned (declared) in a block are only valid within that block.
foobar {
i = 20 # local variable 'i' is declared
...
}
# 'i' is undefined here
foobar a, b do
i = 11 # declaration of a totally different variable 'i'
...
end
Like most methods, an iterator's return value is nil if it is interrupted by break from within a block. When break has
an argument, that value will become the iterator's return value.
yield
Example:
yield data
Syntax:
Passes the argument(s) as the block's argument(s) and evaluates the block. yield is used within MethodDefinition
to define iterators.
def foo
yield(1,2)
end
Assignment of the block argument(s) is carried out according to the rules of multiple assignment. If no block is
supplied to the method that executed yield (i.e., it is not an iterator), throws a LocalJumpError exception.
yield returns the result of the block's last evaluated expression. If block execution has been interrupted by next,
returns nil. When next has an argument, that value will become yield's return value.
Class Definitions
Example:
Syntax:
Defines a class. Class names are identifiers beginning with an uppercase letter.
Class definitions assign a class to a constant specified by an identifier (in Ruby, classes and objects together are
one instance of the Class class.)
When a class is already defined, writing a class definition with the same class name will add to the existing class
definition.
class Foo
def bar
end
end
In a class definition, self is that class itself; otherwise, it is no different than a top-level definition. Class definitions
can contain arbitrary expressions that will be executed when the class is defined.
Class definitions can operate as nests. In the following example, there is absolutely no functional relationship
(such as inheritance) between the outer class Foo and the inner class Bar, other than the fact that the constant
Bar is Foo's inner constant Foo::Bar. Class nests group together semantically related classes into the outer class
or module, and can be used to express an inclusion relationship.
class Foo
class Bar
end
end
Class definitions return the result of the last evaluated expression. If that expression does not return a value, the
class definition returns nil.
Module Definitions
Example:
module Foo
def test
:
end
:
end
Syntax:
module identifier
expr ..
end
Defines a module. Module names are identifiers beginning with an uppercase letter.
Module definitions assign a module to a constant specified by an identifier. In Ruby, classes and objects together
are one instance of the Class class.)
When a module is already defined, writing a module definition with the same module name will add to the existing
module definition.
Module definitions return the result of the last evaluated expression. If that expression does not return a value, the
module definition returns nil.
Method Definitions
Example:
def fact(n)
if n == 1 then
1
else
n * fact(n-1)
end
end
Syntax:
def methodname ['(' [arg ['=' default]] ... [',' '*' arg] ')']
expr ..
[rescue [error_type,..] [then]
expr ..]..
[ensure
expr ..]
end
Defines a method. In other words, defines the method of a class or module if within the definition of that class or
module. If top-level, defines methods that can be called from anywhere. This kind of method can be used like
functions are in other scripting languages.
Method names can be normal identifiers or redefinable operators (==, +, -, and so on; see Operator Expressions.
When a default expression has been provided to a dummy argument, it becomes the default value when the actual
argument is omitted through a method call. The default expression is evaluated at the time of the call and in the
context of the method definition.
When the last dummy argument has a * immediately before it, the remaining actual arguments are all stored in this
argument as an array.
Example:
# with everything
def foo(arg, arg2, arg3 = nil, *rest)
# operator format
def ==(other)
def +(other)
def *(other)
For method definition, each type of dummy argument can only be specified according to the following sequence.
Any of these types of arguments can be omitted.
# unary plus/minus
def +@
def -@
# element substitution
def foo=(value) # obj.foo = value
# [] and []=
def [](key) # obj[key]
def []=(key, value) # obj[key] = value
def []=(key, key2, value) # obj[key, key2] = value
Furthermore, a begin expression as well as rescue and/or ensure clauses can be specified to trap exceptions
when executing a method.
Method Evaluation
When a method is called, its expressions are evaluated in the following order:
Everything is evaluated in the method's context, including the argument's default expression.
The method's return value is the value passed to return. When return is not called, returns the value of the last
evaluated expression in the method, before any ensure clause is executed.
foo
def foo
print "foo\n"
end
Singleton-Method Definitions
Example:
def foo.test
print "this is foo\n"
end
Syntax:
def expr '.' identifier ['(' [ argument ['=' default]] ... [',' '*' argument ]')']
expr ..
[rescue [error_type,..] [then]
expr ..]..
[else
expr ..]
[ensure
expr ..]
end
A singleton method belongs to a certain object and not to a class. Singleton-method definitions can be nested.
The singleton methods of a class carry over to its subclasses. In other words, they act like the class methods in
other object-oriented languages.
In Ruby, class methods are the methods specific to a class. Classes are also objects, so these specific methods
can be defined like regular objects.
Therefore, when a method in a class object is defined in some way, that object becomes a class method.
Specifically, these methods can be defined in the following way (as can modules):
# singleton method
class Hoge
def Hoge.foo
end
end
# even if the class name changes, you don't have to change the method
class Hoge
def self.baz
end
end
Definition Operations
alias
Example:
Syntax:
Assigns an alias to a method or global variable. Specifies an identifier or a Symbol as the method name
(expressions like obj.method are not permitted). alias's argument performs no evaluation of method calls or the
like.
An aliased method carries over that method definition, retaining it even if the original method is redefined. This can
be used when you want to change the actions of a given method, then use the result of the original method in the
redefined method.
Standard Library
{ Built-in Functions
{ Built-in Variables
{ Built-in Classes
Object
Array
Exception
FalseClass
Hash
IO
File
MatchData
Module
Class
NilClass
Numeric
Integer
Bignum
Fixnum
Float
Proc
Range
Regexp
String
Symbol
Time
TrueClass
{ Built-in Modules
Comparable
Enumerable
Errno
FileTest
GC
Kernel
Marshal
Math
{ Built-in Exception Classes
Built-in Functions
Strictly speaking, they aren't functions in Ruby, but since methods defined in the Kernel module can be called from
anywhere, they can be used like functions are in other languages. Carefully consider the repercussions of
redefining the methods here.
block_given?
Returns true when the method has been supplied with a block; otherwise, returns false. See Iterator for
details.
Executes the block and returns its value. If a throw with the same name as tag takes place while the block is
running, the return value will be that throw's second argument.
break cannot break out all nested loops at once. Use catch in these circumstances.
catch(:loop1) {
for i in 1..2
for j in 1..2
throw :loop1, j
end
end
}
eval(expr)
Evaluate the string expr as a Ruby program and returns the result.
exit
exit throws a SystemExit exception to terminate the program, so it can be trapped by a rescue clause where
necessary.
loop { ... }
open(file[, mode])
open(file[, mode]) {|io| ... }
Opens file and returns a File object. mode specifies one of the following strings. When mode is omitted, the
default is "r".
The "b" flag can also be added to any of these (in the format "r+b") to open the file in binary mode.
When open is called along with a block, it opens the file, executes the block, then closes the file when
execution is complete. In this case, returns the result of the block evaluation. That is:
Outputs obj in a human-readable format. Identical to the following code (see Object#inspect):
In Ruby, the usual output destination would be standard output. This method is redefined in RGSS to output
to a Windows message box.
Returns nil.
print(arg[, ...])
Prints the arguments in order. If a non-string object has been supplied as an argument, it will be converted
into a string with to_s and printed. However, if the argument is nil, it will print the string "nil".
In Ruby, the usual output destination would be standard output. This method is redefined in RGSS to output
to a Windows message box.
Returns nil.
raise
raise(message)
raise(exception)
raise(error_type, message)
rand(max)
Creates a random integer in the range 0 ≤ integer < max. Automatically calls srand if it hasn't already been
called.
If max is nil or 0, uses Float to return a random number in the range 0 ≤ real number < 1.
Interprets the string format as does C's sprintf, returning a string of formatted arguments.
srand([seed])
Sets the rand random number seed and returns the old initial value. If seed is omitted, uses the current time
(or a similar value) as the seed.
throw(tag[, value])
Escapes (across methods) to the end of a catch block with the same tag. If there is no catch with the same
tag, the thread terminates with NameError. value will be the return value of the catch.
Built-in Variables
Built-in variables are a type of global variable, but their values are not only used globally.
Local Scope
$~
The information about the last match in the current scope (MatchData object). Setting this variable changes
the values of $&, $1 ... $9, etc.
Identical to Regexp.last_match.
$&
The string matched by the last successful pattern match in this scope, or nil if the last pattern match failed.
Identical to Regexp.last_match[0]
$1
$2
$3 ...
Contains the subpattern from the corresponding set of parentheses in the last successful pattern matched, or
nil if the last pattern match failed.
Global Scope
$!
$DEBUG
The debug mode flag. RGSS sets this flag during playtesting.
There are some differences in exception behavior, etc., while in Ruby's debug mode, but you need not be
concerned about them in RGSS.
Built-in Classes
{ Object
Array
Exception
FalseClass
Hash
IO
File
MatchData
Module
Class
NilClass
Numeric
Integer
Bignum
Fixnum
Float
Proc
Range
Regexp
String
Symbol
Time
TrueClass
Object
The superclass of all classes. Defines the general behavior of objects.
Included Modules
{ Kernel
Methods
self == other
Checks if self and other are equal. By default, has the same effect as equal?.
This method is mostly used for comparison within case statements. By default, acts like Object#==, but this
behavior can be redefined in the subclass to implement an ownership check.
class
clone
dup
Creates a copy of the object. clone returns a complete clone of the original object, including freeze status
and singleton methods, while dup duplicates the object contents only.
Note that clone and dup perform only a shallow copy. They duplicate the object itself, but nothing it points to
(such as array elements).
obj.equal?(obj.clone)
obj == obj.clone
Attempting to duplicate true, false, nil, Numeric objects, Symbol objects, and the like result in TypeError
exceptions.
equal?(other)
When other is self, returns true. This method must not be redefined.
freeze
Prohibits an object's contents from being modified. Modifying a frozen object throws a TypeError exception.
frozen?
Returns true when the object's contents are prohibited from being modified.
inspect
instance_of?(klass)
Returns true when self is a direct instance of the class klass. When obj.instance_of?(c) is true, obj.kind_of?
(c) is always true as well.
is_a?(mod)
kind_of?(mod)
Returns true when self is the class mod (or its subclass). or a class (or its subclass) that includes the module
mod.
module M
end
class C < Object
include M
end
class S < C
end
obj = S.new
p obj.is_a? S # true
p obj.is_a? M # true
p obj.is_a? C # true
p obj.is_a? Object # true
p obj.is_a? Hash # false
nil?
object_id
Returns a unique integer for each object. The integers are assigned to objects arbitrarily.
to_ary
to_hash
to_int
to_s
Returns the string representation of the object. This method is used internally by print and sprintf.
When non-string objects are passed to arguments in print and sprintf, use this method to convert the objects
to strings.
to_str
Private Method
initialize
The initialization method for user-defined classes. This method is called from Class#new to initialize a newly
created object. The default behavior is to do nothing; it is assumed that this method will be redefined in the
subclass as needed. The argument given to Class#new will be passed to initialize as is.
Array
The array class. The elements of an array are arbitrary Ruby objects. See Array Expressions for more information.
Superclass
{ Object
Included Modules
{ Enumerable
Methods
self[nth]
Retrieves the nth item from an array. The index starts from zero. If the nth value is negative, counts
backward from the end of the array (the index of the last element is -1). If the nth element does not exist in
the array, returns nil.
self[start, length]
Returns an array containing length items from start. If the start value is negative, counts backward from the
end of the array (the index of the last element is -1).If length is longer than the length of the array from start,
the length of the overlong portion is ignored. Returns nil if length is negative.
self[nth]=val
Changes the nth element of the array into val. If nth is outside the array range, the array will automatically be
extended. The extended region will be initialized by nil.
Returns val.
self[start, length]=val
Replace the length items from index start with the contents of val. If val is not an array, the items will be
replaced by the contents of val.to_ary or [val]. Returns val .
ary = [0, 1, 2, 3]
ary[1, 2] = ["a", "b", "c"]
p ary # => [0, "a", "b", "c", 3]
ary[2, 1] = 99
p ary # => [0, "a", 99, "c", 3]
ary[1, 0] = ["inserted"]
p ary # => [0, "inserted", "a", 99, "c", 3]
self + other
Returns a new array with the concatenated contents of self and other. If other is not an array, uses the return
value of other.to_ary. If that return value is not an array, throws a TypeError exception.
a = [1, 2]
b = [8, 9]
p a + b # => [1, 2, 8, 9]
p a # => [1, 2] (no change)
p b # => [8, 9] (no change here, either)
self - other
The set subtraction operation. Returns a new array containing self without the elements of other.
The set intersection operation. Returns a new array containing elements belonging to both arrays. Duplicate
elements will be removed.
self | other
The set union operation. Returns a new array containing all elements belonging to either array. Duplicate
elements will be removed.
Compares each element with <=> and returns 1 if self is greater than, 0 if equal to, or -1 if less than other. If
the end of one array is reached with each element being equal, the shorter array will be treated as being the
lesser of the two.
self == other
Compares each element with == and returns TRUE if all elements are equal.
clear
ary = [1, 2]
ary.clear
p ary # => []
clone
dup
Returns a new array with the same contents as the receiver. clone returns a complete clone of the original
array, including freeze status and singleton methods, while dup duplicates the object contents only. Neither
method copies the methods or elements themselves.
compact
compact!
compact returns a new array consisting of self without any nil elements. compact! performs a destructive
update; if modified, returns self, if not modified, returns nil.
concat(other)
Appends (destructively) the other array to the end of self. Returns self.
array = [1, 2]
a = [3, 4]
array.concat a
p array # => [1, 2, 3, 4]
p a # => [3, 4] # this doesn't change
delete(val)
delete(val) { ... }
Delete all elements equal to val (via ==). When elements equal to val are found, returns val.
If there are no elements equal to val, returns nil. However, if a block has been specified, it will be evaluated
and the result returned.
array = [1, 2, 3, 2, 1]
p array.delete(2) # => 2
p array # => [1, 3, 1]
delete_at(pos)
Removes the element at the position specified by pos and returns the removed element. If pos is out of
range, returns nil.
array = [0, 1, 2, 3, 4]
array.delete_at 2
p array # => [0, 1, 3, 4]
Returns self.
empty?
include?(val)
Returns TRUE if the array contains an element equal to val (using ==).
index(val)
Returns the position of the first element equal to val (using ==). If no such element is found, returns nil.
Inserts the value of the second or more arguments immediately before the nth element. Returns self. Defined
as below:
class Array
def insert( n, *vals )
self[n, 0] = vals
self
end
end
length
size
Returns the length of the array. If the array is empty, returns zero.
nitems
pop
Removes the last element and returns it. If the array is empty, returns nil.
p array.pop # => 1
p array.pop # => nil
p array # => []
Returns self.
array = [1, 2, 3]
array.push 4
array.push [5, 6]
array.push 7, 8
p array # => [1, 2, 3, 4, [5, 6], 7, 8]
reverse
reverse!
reverse returns a new array of all elements in reverse order. reverse! destructively updates the elements in
the array.
shift
Removes the first element of the array and returns it. The remaining elements are moved up to fill the gap. If
the array is empty, returns nil.
sort
sort!
sort {|a, b| ... }
sort! {|a, b| ... }
Sorts the contents of the array. If called with a block, it passes two arguments to the block, then uses the
result to compare. Without a block, it compares elements with the operator <=>. sort! destructively updates
the elements in the array.
sort returns a new, sorted array, while sort! always returns self.
uniq
uniq!
uniq returns a new array by removing duplicate elements. The remaining elements will then be shifted
forward to fill the gaps. uniq! performs destructive deletion and returns self if deletion was performed and nil
if it was not.
Returns self.
Exception
The ancestor class of all exceptions.
Superclass
{ Object
Class Method
Exception.new([error_message])
Creates and returns a new exception object. A string indicating an error message can be supplied as an
argument. This message will become the value of the message attribute (below) and will be displayed by the
default exception handler.
Methods
exception([error_message])
Returns self when no argument is specified. Otherwise, creates a copy of itself with the message attribute as
error_message and returns it.
backtrace
z "#{sourcefile}:#{sourceline}:in '#{method}'"
(within methods)
z "#{sourcefile}:#{sourceline}"
message
FalseClass
The false class. false is the only instance of the FalseClass class. false, like nil, denotes a FALSE condition, while
all other objects are TRUE.
Superclass
{ Object
Methods
self | other
self ^ other
Hash
The hash class. See Hash Expressions for more information.
Superclass
{ Object
Included Modules
{ Enumerable
Methods
self[key]
Returns the value mapped to key. If the corresponding key is not registered, returns the default value (or nil if
not specified).
self[key]=value
clear
clone
dup
Returns a new hash with the same contents as the receiver. Using clone on a frozen hash will return a
similarly frozen hash, but dup returns an unfrozen hash with identical contents.
Returns value.
delete(key)
delete(key) {|key| ... }
Deletes the mapping from key. Returns the removed value, or nil if there is no value corresponding to key.
When the method has been supplied with a block, it will be evaluated and the results returned if there is no
match for key.
empty?
has_key?(key)
include?(key)
has_value?(value)
Returns true when the hash includes value as a value as determined by ==.
index(val)
Returns the key corresponding to val. If there is no corresponding element, returns nil.
keys
length
size
values
IO
The IO class provides basic IO functions.
Superclass
{ Object
Included Modules
{ Enumerable
Methods
binmode
Converts the stream into binary mode. The only way to revert to normal mode is to reopen the stream.
Returns self.
close
Returns nil.
Returns self.
Returns self.
eof?
Returns true when the stream reaches the end of the file.
pos
pos=n
read([length])
Reads length bytes and returns the string. If length is omitted, reads all data until the end of the file.
If the IO has already reached the end of the file, returns nil.
Throws an Errno::EXXX exception if the data read fails and an ArgumentError exception if length is negative.
readlines([rs])
Reads all the data and returns an array whose elements consist of the lines read. If the IO has already
reached the end of the file, returns the empty array [].
Lines are separated by the string indicated in the argument rs, whose default value is "\n".
Specify nil for rs and the lines will not be separated. Specify the empty string "" and consecutive linefeeds will
be treated as line separators (paragraph mode).
write(str)
Outputs str to the IO port. If str is not a string, tries converting it to a string with to_s.
Returns the actual number of bytes written. Throws an Errno::EXXX exception if the output action fails.
File
The file access class, normally created by open or File.open.
Open file objects that cannot be referenced will be closed and discarded by the next garbage collection.
Superclass
{ IO
Class Methods
File.mtime(filename)
File.basename(filename[, suffix])
Returns the final slash-delimited component of filename. If suffix is supplied and is identical to the end of
filename, filename is returned without the suffix.
File.delete(filename ... )
Deletes a file or files and returns the number of files deleted. If deletion fails, throws an Errno::EXXX
exception.
File.dirname(filename)
Returns all but the final slash-delimited component of filename. Returns "." (the current directory) for a
filename that does not include a slash.
File.expand_path(path[, default_dir])
Returns a string containing path's expanded absolute path. If path is relative, sets default_dir as the base
directory. If default_dir is nil or missing, uses the current directory.
File.extname(filename)
Returns filename's extension (the string after the final dot). Dots in directory names or at the start of
filenames are not considered to be denoting extensions. If filename contains no extension, returns an empty
string.
File.open(path[, mode])
File.open(path[, mode]) {|file| ... }
Opens the file specified by path and returns the file object. If file opening fails, throws an Errno::EXXX
exception.
Blocks can be specified for open(). When called with a block, executes the block with the given file object.
The file will be closed automatically after executing the block.
When a block is specified, the return value of this method is the result of the block's evaluation.
File.rename(from, to)
Renames file, moving it to a different directory as required. If a file already exists at the destination, it is
overwritten.
Returns 0 when file movement is successful; when it fails, throws an Errno::EXXX exception.
Methods
mtime
path
MatchData
The class handling regular expression match data. Instances of this class can be obtained via
{ Regexp.last_match,
{ Regexp#match, and
{ $~.
Superclass
{ Object
Methods
self[n]
Returns the nth substring. 0 signifies the entire matching string. When the value of n is negative, it is treated
as a backwards index (the final element being in the position -1). When the nth element does not exist,
returns nil.
/(foo)(bar)(BAZ)?/ =~ "foobarbaz"
p $~.to_a # => ["foobar", "foo", "bar", nil]
p $~[0] # => "foobar"
p $~[1] # => "foo"
p $~[2] # => "bar"
p $~[3] # => nil (doesn't match)
p $~[4] # => nil (out of range)
p $~[-2] # => "bar"
post_match
pre_match
to_a
to_s
Module
Superclass
{ Object
Method
This method is mostly used for comparison within case statements. Returns true if obj has an
Object#kind_of? relationship with self. In other words, case can be used to check the owner relationship of
classes and modules.
str = String.new
case str
when String # evaluates String === str
p true # => true
end
Private Methods
attr_accessor(name ... )
Defines both the read and write methods for the attribute name, where name is specified by Symbol or a
string.
def name
@name
end
def name=(val)
@name = val
end
attr_reader(name ... )
Defines the read method for the attribute name, where name is specified by Symbol or a string.
def name
@name
end
attr_writer(name ... )
Defines the write method for the attribute name (name=), where name is specified by Symbol or a string.
def name=(val)
@name = val
end
include(module ... )
Includes the specified modules' properties (methods and constants). Returns self. include is used to
implement a mix-in in place of a multiple inheritance.
class C
include FileTest
include Math
end
Module capabilities are included by inserting modules into a class inheritance. Therefore, when searching for
methods, included modules will be given priority over superclasses.
If the same module is included two or more times, the second and later instances will be ignored.
Furthermore, executing an include that results in a recursive module inheritance will throw an ArgumentError
exception.
Class
The class of classes. More accurately speaking, each class has its own unnamed "metaclass", and Class is the
class of these metaclasses. This relationship is a little complicated, but it is not especially important to keep in
mind while using Ruby.
Superclass
{ Module
Method
new( ... )
Creates a class instance and returns it. This method's arguments, including block arguments, are passed to
initialize.
NilClass
The nil class of nil. nil is the sole instance of this class, signifying FALSE along with the false object. All other
objects are true.
Superclass
{ Object
Methods
self | other
self ^ other
nil?
to_a
to_f
Returns 0.0.
to_i
Returns 0.
to_s
Numeric
Numeric is the abstract class for numbers. In Ruby, operations are possible among different numerical classes.
Operations and comparison methods (+, -, *, /, <=>), etc. are defined in a subclass. For increased efficiency,
methods identical to the Numeric method may also be redefined in a subclass.
Superclass
{ Object
Included Modules
{ Comparable
Methods
+ self
Returns self.
- self
abs
ceil
Returns the smallest integer equal to or greater than self (i.e., the ceiling).
floor
Returns the largest integer that does not exceed self (i.e., the floor).
integer?
round
truncate
Integer
The abstract class for integers. Its subclasses are Fixnum and Bignum. These two types of integers are
automatically converted into one another according to their values. Integers can be treated as infinite bit strings for
bit operations.
Superclass
{ Numeric
Methods
self[nth]
Returns 1 if the nth bit of the integer is set (with the LSB, or least significant bit, at position 0), otherwise
returns 0.
self[nth]=bit is not an Integer method because the associated Numeric class is immutable.
self + other
self - other
self * other
self / other
self % other
self ** other
Arithmetic operators. Compute the sum, difference, product, quotient, remainder, and exponent respectively.
Compares self with other; returns a positive integer if self is larger, 0 if the two are equal, and a negative
integer if self is smaller.
self == other
self < other
self <= other
self > other
self >= other
Relational operators.
~ self
self | other
self & other
self ^ other
Bit operators. Compute bitwise negation, logical OR, logical AND, and logical XOR respectively.
The signed bit (MSB or most significant bit) is retained in a right shift.
chr
Returns a 1-byte string corresponding to the numeric position in the character set. For example, 65.chr
returns "A".
The integer must be within the range of 0 to 255. Calling this method with an out-of-range integer will throw a
RangeError exception.
Iterates from self to min, decrementing by 1. If self < min, does nothing.
next
succ
Iteratively evaluates a block from self, incrementing by step, until limit is about to be surpassed. step can
also be a negative number.
Returns self.
Iterates self number of times, from 0 to self-1. If self is negative, does nothing.
Returns self.
to_f
to_s([base])
If an argument is specified, it will be used as the base number for conversion. If a base outside the range of
2-36 is specified, an ArgumentError exception will be thrown.
Iterates from self to max, incrementing by 1. If self > max, does nothing.
Returns self.
Bignum
The class for long integers, limited only by memory size. The result of an operation is automatically converted into
a Fixnum if its value is within range; conversely, if the value is out of Fixnum range, it is extended into a Bignum.
For bit operations, Bignum can be considered to be an infinite 2's complement bit string. Negative numbers in
particular can operate as a string of 1 bits extending indefinitely to the left. Mixing Bignum with Float can result in
digit cancellation errors upon conversion.
Superclass
{ Integer
Fixnum
The class for fixed-length integers that fit into the machine's pointer, which is usually 31 bits long. If the result of an
operation is out of Fixnum range, it is automatically extended into a Bignum.
Superclass
{ Integer
Methods
id2name
Returns the string corresponding to a Symbol integer (obtained with Symbol#to_i). If there is no symbol that
corresponds to the integer, returns nil.
to_sym
Returns the Symbol object corresponding to the integer value of the object's self. If there is no symbol that
corresponds to the integer, returns nil.
Float
The floating point value class. The implementation of Float is the same as in C.
Superclass
{ Numeric
Methods
self + other
self - other
self * other
self / other
self % other
self ** other
Arithmetic operator. Computes the sum, difference, product, quotient, remainder, and exponent.
Compares other with self; returns a positive integer if self is larger, 0 if the two are equal, and a negative
integer if self is smaller.
self == other
self < other
self <= other
self > other
self >= other
Relational operator.
finite?
infinite?
Returns 1 when a value is positive and infinite; returns -1 when a value is negative and infinite. Otherwise,
returns nil. The floating point zero ensures infinite division.
inf = 1.0/0
p inf
p inf.infinite?
=> Infinity
1
inf = -1.0/0
p inf
p inf.infinite?
=> -Infinity
-1
nan?
Returns TRUE when a value is NaN (not a number). The floating point zero ensures the result of division by
0 is NaN.
nan = 0.0/0.0
p nan
p nan.nan?
=> NaN
true
Range
The range object class. See Range Expressions for more information.
Superclass
{ Object
Included Module
{ Enumerable
Methods
This method is mostly used for comparison within case statements. Returns true if other is within range.
begin
first
end
last
Returns the end point, regardless of whether the range object is inclusive of the end point.
p (1..5).end # => 5
p (1...5).end # => 5
exclude_end?
Proc
Proc is a procedure object in which both a block and its context (local variable scope and stack frame) have been
encapsulated as an object. Proc can be used like an unnamed function, except that it does not have its own local
variable scope.
We can see that Proc retains a local variable scope, however, by observing that the variable var can be
referenced, as in the example below:
var = 1
$foo = Proc.new { var }
var = 2
def foo
$foo.call
end
p foo # => 2
Superclass
{ Object
Class Method
Proc.new
Proc.new { ... }
Encapsulates a block, along with its context, into an object and returns it.
If no block is specified, but the method that called Proc.new contains a block, that block will be created as a
Proc object and returned.
Method
call(arg ... )
Executes a procedure object and returns the result. Arguments are assigned to block parameters as is
(according to the rules of multiple assignation).
Regexp
The regular expression class. See Regular Expressions for details.
Superclass
{ Object
Class Methods
Regexp.last_match
Returns the MatchData object for the last regular expression match performed in the current scope. This
method call is identical to a $~ reference.
/(.)(.)/ =~ "ab"
p Regexp.last_match # => #<MatchData:0x4599e58>
p Regexp.last_match[0] # => "ab"
p Regexp.last_match[1] # => "a"
p Regexp.last_match[2] # => "b"
p Regexp.last_match[3] # => nil
Regexp.last_match([nth])
If the integer nth is 0, returns the matching string ($&). Otherwise, returns the substring matching the nth set
of parentheses ($1, $2, ...). When there are no corresponding parentheses or no matches, returns nil.
/(.)(.)/ =~ "ab"
p Regexp.last_match # => #<MatchData:0x4599e58>
p Regexp.last_match(0) # => "ab"
p Regexp.last_match(1) # => "a"
p Regexp.last_match(2) # => "b"
p Regexp.last_match(3) # => nil
Because Regexp.last_match, with no arguments, returns nil when the entire regular expression does not
match, the format last_match[1] will throw a NameError exception. On the other hand, last_match(1) returns
nil.
Methods
self =~ string
self === string
Matches the string string to a regular expression. If the argument is not a string or does not match, returns
false; if it matches, returns true.
match(str)
Identical to self=~str, except that it does not return a MatchData object. If there is no match, returns nil.
When only the substring matching the regular expression is needed, use match(str) like this:
bar = /foo(.*)baz/.match("foobarbaz").to_a[1]
to_s
Creates and returns a string expression for a regular expression. Preserves the meaning of the returned
string even if the string is embedded in another regular expression.
re = /foo|bar|baz/i
p re.to_s # => "(?i-mx:foo|bar|baz)"
p /#{re}+/o # => /(?i-mx:foo|bar|baz)+/
However, some regular expressions with backreferences may not work as expected. This is because
backreferences can only be specified by number at present.
# => /(baz)(?-mix:(foo|bar)\1)/
String
The string class. Can handle byte sequences of arbitrary lengths. See String Literals for details.
The String class itself behaves like a byte sequence. Use scan(/./), etc. to extract characters from a multibyte
string one at a time.
Superclass
{ Object
Included Modules
{ Comparable
{ Enumerable
Methods
self + other
self * times
Creates and returns a new string consisting of the string contents repeated times times.
Compares self with other by ASCII order; returns a positive integer if self is larger, 0 if the two are equal, and
a negative integer if self is smaller.
self == other
self[nth, len]
Returns a len-byte-long substring found at the nth byte. When nth is negative, counts from the end of the
string.
self[regexp]
Returns the first substring matching regexp. Matching information can be configured in the built-in variable
$~.
self[nth, len]=val
Replaces the len-byte-long substring found at the nth byte with the string val. When nth is negative, counts
from the end of the string.
Returns val .
self[regexp]=val
Replaces the first substring matching the regular expression regexp with the string val.
Returns val.
clone
dup
Returns a new string with the same contents as the original string. Using clone on a frozen string will return a
similarly frozen string, but dup returns an unfrozen string with identical contents.
concat(other)
downcase
downcase!
downcase creates and returns the modified string. downcase! modifies and returns self, but if no characters
were replaced, returns nil.
Returns self.
empty?
Replaces all substrings matching pattern with the results of the block evaluation. The matching substring is
passed to the block as an argument. The built-in variable $<digits> can be referenced within the block.
gsub creates and returns the post-replacement string. gsub! modifies and returns self, but if no characters
were replaced, returns nil.
include?(substr)
If substr is a Fixnum from 0 to 255, it is determined to be a character code and if that character is included, it
returns true.
index(pattern[, pos])
Performs a search for the substring from left to right. Returns the left-hand position of the found substring. If
nothing is found, nil is returned.
The pattern argument is used to specify the substring to search for, using a text string, an integer from 0 to
255, or a regular expression.
If pos is provided, the search starts from that position. The value of pos when it is omitted is 0.
insert(nth, other)
Inserts the string other immediately before the character in the nth position. Returns self.
to_sym
length
size
scan(re)
scan(re) {|s| ... }
Repeatedly matches against self with the regular expression re and returns an array of matching substrings.
p "foobarbazfoobarbaz".scan(/ba./)
# => ["bar", "baz", "bar", "baz"]
p "abcde".scan(/./)
# => ["a", "b", "c", "d", "e"]
When called with a block specified, the matching substrings become the block's parameters. (If parentheses
are included, an array of strings that match the patterns in parentheses becomes the block's parameter.) If a
block is specified, returns self.
"foobarbazfoobarbaz".scan(/ba./) {|s| p s}
# => "bar"
"baz"
"bar"
"baz"
slice(nth, len)
slice(regexp)
Identical to self[].
slice!(nth, len)
slice!(regexp)
Removes a specified range (see self[]) from a string and returns the removed substring.
Replaces the first substring matching pattern with the results of the block evaluation.
sub creates and returns the post-replacement string. sub! modifies and returns self, but if no characters were
replaced, returns nil.
to_f
Interprets the string as a base-10 expression and converts it into a floating point integer (Float).
to_i([base])
The default is base-10. By specifing base, you can perform base 2-36 conversions as well.
upcase
upcase!
downcase creates and returns the modified string. downcase! modifies and returns self, but if no characters
were replaced, returns nil.
Symbol
The class that expresses symbols. See Symbol for more information.
Superclass
{ Object
Methods
id2name
to_i
In Ruby, reserved words, variable names, method names, and the like are controlled by these integers.
Integers corresponding to objects (obtained via Object#object_id) and those corresponding to symbols are
separate items.
Time
The time class.
Superclass
{ Object
Included Module
{ Comparable
Class Method
Time.now
Methods
self + other
self - other
When other is a Time object, returns the difference between the two times with Float. If other is a numeric
Compares times. other must be a Time object or a numeric value; if a numeric value, the times are
compared in terms of seconds since the epoch began.
strftime(format)
Returns the time, having been converted into a string via a format string. The format string may be specified
with the following:
z %A
z %a
z %B
z %b
z %c
z %d
z %H
z %I
z %j
z %M
Minutes (00-59)
z %m
z %p
AM or PM
z %S
z %U
Week of the year, the first week starting with the first Sunday (00-53)
z %W
Week of the year, the first week starting with the first Monday (00-53)
z %w
z %X
Time
z %x
Date
z %Y
Year, 4-digit
z %y
z %Z
Time zone
z %%
The character %
sec
min
hour
mday
mon
year
wday
TrueClass
The true class. true is the only instance of the TrueClass class. true is a representative object that denotes a
TRUE condition.
Superclass
{ Object
Methods
self | other
self ^ other
Built-in Modules
{ Comparable
{ Enumerable
{ Errno
{ FileTest
{ GC
{ Kernel
{ Marshal
{ Math
Comparable
A mix-in allowing for relational operations. Classes including this module must define the basic relational operators
<, =, and >. All other relational operators can be derived through use of those definitions.
Methods
self == other
between?(min, max)
Returns TRUE when self falls within a range from min to max, inclusive.
When self <=> min or self <=> max returns nil, throws an ArgumentError exception.
Enumerable
A mix-in for repeating classes. This module's methods are all defined via each, so each must be defined in any
class which includes this module.
Method
all?
all? {|item| ... }
Returns TRUE when all items are true. If any item is false, immediately returns FALSE.
When using a block, evaluates the block against each item and returns TRUE if all outcomes are true. If the
block returns FALSE at any time, immediately returns FALSE.
any?
any? {|item| ... }
Returns FALSE when all items are false. If any item is true, immediately returns TRUE.
When using a block, evaluates the block against each item and returns FALSE if all outcomes are false. If
the block returns TRUE at any time, immediately returns TRUE.
Returns the first item that tested as true during the block evaluation. If no item was true, returns nil.
Returns an array of all items that tested as true during the block evaluation. If no item was true, returns an
empty array.
include?(val)
Returns TRUE when the list includes an item that satisfies the relationship val ==.
max
Returns the largest item. Assumes all items are comparable via the <=> method.
Compares each item based on the block's evaluated value and returns the largest item.
Anticipates a block value that will be a positive integer when a>b, 0 when a==b, and a negative integer when
a<b. When the block returns a non-integer, throws a TypeError exception.
min
Returns the smallest item. Assumes all items are comparable via the <=> method.
Compares each item based on the block's evaluated value and returns the smallest item.
Anticipates a block value that will be a positive integer when a>b, 0 when a==b, and a negative integer when
a<b. When the block returns a non-integer, throws a TypeError exception.
sort
sort {|a, b| ... }
When not using a block, calls the <=> against each item and sorts based upon those results.
To sort using other methods besides <=>, select a block; the items will be sorted based on the evaluation of
this block. Anticipates a block value that will be a positive integer when a>b, 0 when a==b, and a negative
integer when a<b. When the block returns a non-integer, throws a TypeError exception.
to_a
entries
Errno
A module containing exceptions corresponding to system call errors.
Inner Classes
These are representative exception classes. Many others are defined as well, but you need not be concerned
about them.
E2BIG
The argument list is too long.
EACCES
Access permission was denied.
EAGAIN
Cannot create any more processes.
EBADF
Invalid file number.
ECHILD
No child process exists.
EDEADLOCK
Possibility of a resource deadlock.
EDOM
The value of the numerical data function's argument is outside the function's domain.
EEXIST
FileTest
A module containing file test functions.
Module Functions
FileTest.exist?(filename)
FileTest.directory?(filename)
FileTest.file?(filename)
FileTest.size(filename)
Returns the size of filename. If filename does not exist, throws an Errno::EXXX exception (most likely
Errno::ENOENT).
GC
A module that controls garbage collection in the Ruby interpreter.
Module Method
GC.disable
Returns the previous halt state (if halted, returns TRUE; if garbage collection was enabled, returns FALSE).
GC.enable
Returns the previous halt state (if halted, returns TRUE; if garbage collection was enabled, returns FALSE).
GC.start
Returns nil.
Kernel
A module defining the methods that can be referred to by all classes. Object classes are included in this module.
The methods explained on the Built-in Functions page are defined in this module.
Object class methods are defined in this module. This ensures compatibility with top-level method redefinition.
Marshal
A module providing the capability to write a Ruby object to and read it from a file (or string array).
Module Functions
Some objects may not be writeable to file, such as in instances of File or MatchData, or with objects that
define unusual methods. When attempting to write such objects to file, a TypeError will occur.
port specifies an instance of IO (or a subclass). In this case, returns port. When omitted, dump returns the
object's dump as a string.
When limit is specified, no objects linked at or deeper than limit can be dumped (100 levels is the default.
When limit is negative, no depth checking is performed.
Marshal.load(port)
Reads marshal data from port (i.e., the string output from Marshal.dump) and creates an object with the
same state as the original object. port specifies an instance of IO (or a subclass).
Math
A module that supports floating point calculations.
Module Functions
Math.acos(x)
Math.asin(x)
Math.atan(x)
Values that can be returned have ranges of [0, +π], [-π/2, +π/2], and (-π/2, +π/2) respectively.
In acos(x), and asin(x), x must be in the range -1.0 <= x <= 1 (normally returns NaN).
acos() and asin() will throw an Errno::EDOM exception for arguments out of range.
Math.atan2(y, x)
Math.acosh(x)
Math.asinh(x)
Math.atanh(x)
In atanh(x), x must be in the range -1.0 < x < 1 (normally throws an Errno::EDOM exception).
Math.cos(x)
Math.sin(x)
Math.tan(x)
Returns the value of the trigonometric functions of x in radians, in the range [-1, 1].
Math.cosh(x)
Math.sinh(x)
Math.tanh(x)
Math.erf(x)
Math.erfc(x)
Returns the values of the error function (erf) and complementary error function (erfc) of x.
Math.exp(x)
Math.frexp(x)
Math.hypot(x, y)
Math.ldexp(x, exp)
Math.log(x)
x must be a positive value (normally returns NaN for negative values and -Infinity for 0).
Negative arguments out of range throw Errno::EDOM exceptions, while a 0 argument throws an
Errno::ERANGE exception.
Math.log10(x)
x must be a positive value (normally returns NaN for negative values and -Infinity for 0).
Negative arguments out of range throw Errno::EDOM exceptions, while a 0 argument throws an
Errno::ERANGE exception.
Math.sqrt(x)
Returns the square root of x. When x is a negative value, throws an ArgumentError exception.
Definitions
p Math::E
# => 2.718281828
PI
p Math::PI
# => 3.141592654
Exception class for each errno. See the Errno module for more on each class name.
SystemStackError
Thrown when a stack level becomes too deep.
TypeError
Thrown when an illegal type is invoked.
ZeroDivisionError
Thrown when dividing by zero.
SystemExit
Terminates the program. See exit for more information.
fatal
A fatal (internal) error. This object is not visible with normal methods.
Game Library
{ RGSS Built-in Functions
{ RGSS Built-in Classes
Bitmap
Color
Font
Plane
Rect
Sprite
Table
Tilemap
Tone
Viewport
Window
RGSSError
{ RGSS Built-in Modules
Audio
Graphics
Input
RPG
{ RPGVX Data Structures
RPG::Map
RPG::MapInfo
RPG::Area
RPG::Event
RPG::Event::Page
RPG::Event::Page::Condition
RPG::Event::Page::Graphic
RPG::EventCommand
RPG::MoveRoute
RPG::MoveCommand
RPG::Actor
RPG::Class
RPG::Class::Learning
RPG::BaseItem
RPG::UsableItem
RPG::Skill
RPG::Item
RPG::Weapon
RPG::Armor
RPG::Enemy
RPG::Enemy::DropItem
RPG::Enemy::Action
RPG::Troop
RPG::Troop::Member
RPG::Troop::Page
RPG::Troop::Page::Condition
RPG::State
RPG::Animation
RPG::Animation::Frame
RPG::Animation::Timing
RPG::CommonEvent
RPG::System
RPG::System::Vechile
RPG::System::Terms
RPG::System::TestBattler
RPG::AudioFile
RPG::BGM
RPG::BGS
RPG::ME
RPG::SE
load_data(filename)
Loads the data file indicated by filename and restores the object.
$data_actors = load_data("Data/Actors.rvdata")
However, it differs in that it can load files from within encrypted archives.
save_data(obj, filename)
save_data($data_actors, "Data/Actors.rvdata")
It is unlikely you will ever use this function during a game, but it is defined as a counterpart to load_data.
Also, the built-in functions p and print are redefined for use in message box output.
Bitmap
The bitmap class. Bitmaps are expressions of so-called graphics.
Sprites (Sprite) and other objects must be used to display bitmaps on the screen.
Superclass
{ Object
Class Methods
Bitmap.new(filename)
Loads the graphic file specified in filename and creates a bitmap object.
Also automatically searches files included in RGSS-RTP and encrypted archives. File extensions may be
omitted.
Bitmap.new(width, height)
Methods
dispose
Frees the bitmap. If the bitmap has already been freed, does nothing.
disposed?
width
height
rect
Performs a block transfer from the src_bitmap box src_rect (Rect) to the specified bitmap coordinates (x, y).
Performs a block transfer from the src_bitmap box src_rect (Rect) to the specified bitmap box dest_rect
(Rect).
Fills the bitmap box (x, y, width, height) or rect (Rect) with color (Color).
Fills in this bitmap box (x, y, width, height) or rect (Rect) with a gradient from color1 (Color) to color2 (Color).
Set vertical to true to create a vertical gradient. Horizontal gradient is the default.
clear
clear_rect(rect) (RGSS2)
get_pixel(x, y)
set_pixel(x, y, color)
hue_change(hue)
This process is time-consuming. Furthermore, due to conversion errors, repeated hue changes may result in
color loss.
blur (RGSS2)
Applies a radial blur to the bitmap. angle is used to specify an angle from 0 to 360. The larger the number,
the rounder the effect.
division is the division number (from 2 to 100). The larger the number, the smoother it will be. This process
can be very time consuming.
Draws a string str in the bitmap box (x, y, width, height) or rect (Rect).
If str is not a character string object, it will be converted to a character string using the to_s method before
processing is performed. (RGSS2)
If the text length exceeds the box's width, the text width will automatically be reduced by up to 60 percent.
Horizontal text is left-aligned by default; set align to 1 to center the text and to 2 to right-align it. Vertical text
is always centered.
As this process is time-consuming, redrawing the text with every frame is not recommended.
text_size(str)
Gets the box (Rect) used when drawing a string str with the draw_text method. Does not include the angled
portions of italicized text.
If str is not a character string object, it will be converted to a character string using the to_s method before
processing is performed.(RGSS2)
Property
font
The font (Font) used to draw a string with the draw_text method.
Color
The RGBA color class. Each component is handled with a floating point value (Float).
Superclass
{ Object
Class Method
Method
Properties
red
The red value (0-255). Values out of range are automatically corrected.
green
The green value (0-255). Values out of range are automatically corrected.
blue
The blue value (0-255). Values out of range are automatically corrected.
alpha
The alpha value (0-255). Values out of range are automatically corrected.
Font
Superclass
{ Object
Class Methods
Font.new([name[, size]])
Font.exist?(name)
Returns TRUE when the specified font exists within the system.
Properties
name
The font name. Include an array of strings to specify multiple fonts to be used in a desired order.
In this example, if the higher priority font Myriad does not exist within the system, the second choice Verdana
will be used instead.
size
bold
italic
shadow (RGSS2)
The flag for shadow text. The default is TRUE. When enabled, a black shadow will be drawn to the bottom
right of the character.
color
The font color (Color). Alpha values may also be used. The default is (255,255,255,255).
Alpha values are also used when drawing shadow text. (RGSS2)
Class Properties
default_name
default_size
default_bold
default_italic
default_shadow (RGSS2)
default_color
Change the default values for each component, to be applied to each new Font object.
Plane
The Plane class. Planes are special sprites that tile bitmap patterns across the entire screen, and are used to
display parallax backgrounds, etc.
Superclass
{ Object
Class Method
Plane.new([viewport])
Methods
dispose
Frees the plane. If the plane has already been freed, does nothing.
disposed?
Properties
bitmap
viewport (RGSS2)
visible
The plane's Z-coordinate. The larger this value, the closer to the player the plane will be displayed. If multiple
objects share the same Z-coordinate, the more recently created object will be displayed closest to the player.
ox
The X-coordinate of the plane's starting point. Change this value to scroll the plane.
oy
The Y-coordinate of the plane's starting point. Change this value to scroll the plane.
zoom_x
The plane's X-axis zoom level. 1.0 denotes actual pixel size.
zoom_y
The plane's Y-axis zoom level. 1.0 denotes actual pixel size.
opacity
The plane's opacity (0-255). Values out of range are automatically corrected.
blend_type
color
The color (Color) to be blended with the plane. Alpha values are used in the blending ratio.
tone
Rect
The rectangle class.
Superclass
{ Object
Class Method
Method
Properties
width
height
Sprite
The sprite class. Sprites are the basic concept used to display characters, etc. on the game screen.
Superclass
{ Object
Class Method
Sprite.new([viewport])
Methods
dispose
Frees the sprite. If the sprite has already been freed, does nothing.
disposed?
flash(color, duration)
Begins flashing the sprite. duration specifies the number of frames the flash will last.
update
Advances the sprite flash or wave phase (RGSS2). As a general rule, this method is called once per frame.
width (RGSS2)
height (RGSS2)
Properties
bitmap
Refers to the bitmap (Bitmap) used for the sprite's starting point.
src_rect
viewport (RGSS2)
visible
The sprite's Z-coordinate. The larger this value, the closer to the player the sprite will be displayed.
If two sprites have the same Z coordinates, the one with the larger Y coordinate will be displayed closer to
the player (RGSS2), and if the Y coordinates are the same, the one that was generated later will be
displayed closer to the player.
ox
oy
zoom_x
The sprite's X-axis zoom level. 1.0 denotes actual pixel size.
zoom_y
The sprite's Y-axis zoom level. 1.0 denotes actual pixel size.
angle
The sprite's angle of rotation. Specifies up to 360 degrees of counterclockwise rotation. However, drawing a
rotated sprite is time-consuming, so avoid overuse.
wave_amp (RGSS2)
wave_length (RGSS2)
wave_speed (RGSS2)
wave_phase (RGSS2)
Defines the amplitude, frequency, speed, and phase of the wave effect. A raster scroll effect is achieved by
using a sinusoidal function to draw the sprite with each line's horizontal position a bit different from the last.
wave_amp is the wave amplitude and wave_length is the wave frequency, and each is specified by number
of pixels.
wave_speed specifies the speed of the wave animation. The default is 360, and the larger the value, the
faster the effect.
wave_phase specifies the phase of the top line of the sprite using an angle of up to 360 degrees. This is
updated each time the update method is called. It is not necessary to use this property unless it is required
for two sprites to have their wave effects synchronized.
mirror
Flag denoting the sprite has been flipped horizontally. If TRUE, the sprite will be drawn flipped.
bush_depth
bush_opacity (RGSS2)
The bush depth and opacity of a sprite. This can be used to represent something like characters' legs being
hidden by bushes.
For bush_depth, the number of pixels for the bush section is specified. The default value is 0.
For bush_opacity, the opacity of the bush section from 0 to 255 is specified. Values that are out of range will
automatically be corrected. The default value is 128.
The bush_opacity value will be multiplied by opacity. For example, if both opacity and bush_opacity are set
to 128, it will be handled as transparency on top of transparency, for an actual opacity of 64.
opacity
The sprite's opacity (0-255). Values out of range are automatically corrected.
blend_type
color
The color (Color) to be blended with the sprite. Alpha values are used in the blending ratio.
Handled separately from the color blended into a flash effect. However, the color with the higher alpha value
when displayed will have the higher priority when blended.
tone
Table
The multidimensional array class. Each element takes up 2 signed bytes, ranging from -32,768 to 32,767.
Ruby's Array class does not run efficiently when handling large amounts of data, hence the inclusion of this class.
Superclass
{ Object
Class Method
Creates a Table object. Specifies the size of each dimension in the multidimensional array. 1-, 2-, and 3-
dimensional arrays are possible. Arrays with no parameters are also permitted.
Methods
Change the size of the array. All data from before the size change is retained.
xsize
ysize
zsize
Properties
self[x]
self[x, y]
self[x, y, z]
Accesses the array's elements. Pulls the same number of arguments as there are dimensions in the created
array. Returns nil if the specified element does not exist.
Tilemap
The class governing tilemaps. Tilemaps are a specialized concept used in 2D game map displays, created
internally from multiple sprites.
Superclass
{ Object
Class Method
Tilemap.new([viewport])
Methods
dispose
Frees the tilemap. If the tilemap has already been freed, does nothing.
disposed?
update
Updates the autotile animation, etc. As a rule, this method is called once per frame.
Properties
bitmaps[index] (RGSS2)
Refers to the bitmap (Bitmap) indicated by the index number (0 - 8) that is used as a tile set.
The correspondence between numbers and sets is illustrated in the table below.。
map_data
Refers to map data (Table). Defines a 3-dimensional array measuring [ horizontal size * vertical size * 3 ].
flash_data
Refers to the flash data (Table) used when showing range of possible movement in simulation games, etc.
Defines a 2-dimensional array measuring [ horizontal size * vertical size ]. This array must be the same size
as the map data. Each element uses 4 bits to represent a tile's flash color in RGB; for example, 0xf84 flashes
in RGB(15,8,4).
passages (RGSS2)
Reference to the passage table (Table). Defines a 1-dimensional array containing elements corresponding to
tile IDs.
viewport (RGSS2)
visible
ox
The X-coordinate of the tilemap's starting point. Change this value to scroll the tilemap.
oy
The Y-coordinate of the tilemap's starting point. Change this value to scroll the tilemap.
Notes
The Z-coordinate of each sprite used to create a tilemap is fixed at a specific value.
Keep these rules in mind when setting the Z-coordinates of any map characters.
Tone
The color tone class. Each component is handled with a floating point value (Float).
Superclass
{ Object
Class Method
Method
Properties
red
The red balance adjustment value (-255 to 255). Values out of range are automatically corrected.
green
The green balance adjustment value (-255 to 255). Values out of range are automatically corrected.
blue
The blue balance adjustment value (-255 to 255). Values out of range are automatically corrected.
gray
The grayscale filter strength (0 to 255). Values out of range are automatically corrected.
When this value is not 0, processing time is significantly longer than when using tone balance adjustment
values alone.
Viewport
The viewport class. Used when displaying sprites in one portion of the screen, with no overflow into other regions.
Superclass
{ Object
Class Methods
Methods
dispose
Frees the viewport. If the viewport has already been freed, does nothing.
This operation will not result in a separate associated object being automatically freed. (RGSS2)
disposed?
flash(color, duration)
Begins flashing the viewport. duration specifies the number of frames the flash will last.
update
Refreshes the viewport flash. As a rule, this method is called once per frame.
Properties
rect
visible
The viewport's Z-coordinate. The larger this value, the closer to the player the plane will be displayed. If
multiple objects share the same Z-coordinate, the more recently created object will be displayed closest to
the player.
ox
The X-coordinate of the viewport's starting point. Change this value to shake the screen, etc.
oy
The Y-coordinate of the viewport's starting point. Change this value to shake the screen, etc.
color
The color (Color) to be blended with the viewport. Alpha values are used in the blending ratio.
tone
Window
The game window class. Created internally from multiple sprites.
Superclass
{ Object
Class Method
Window.new([viewport])
Methods
dispose
Frees the window. If the window has already been freed, does nothing.
disposed?
update
Refreshes the cursor blink and the pause graphic animation. As a rule, this method is called once per frame.
Properties
windowskin
contents
viewport (RGSS2)
cursor_rect
The cursor box (Rect). Sets the window's upper left corner using relative coordinates (-16, -16).
active
visible
pause
The pause graphic's visibility. This is a symbol that appears in the message window when waiting for the
player to press a button. If TRUE, the graphic is visible.
width
height
The window's Z-coordinate. The larger this value, the closer to the player the plane will be displayed. If
multiple objects share the same Z-coordinate, the more recently created object will be displayed closest to
the player.
It is no longer possible to use different Z coordinates for the window's background and its contents. (RGSS2)
ox
The X-coordinate of the starting point of the window's contents. Change this value to scroll the window's
contents.
oy
The Y-coordinate of the starting point of the window's contents. Change this value to scroll the window's
contents.
opacity
The window's opacity (0-255). Values out of range are automatically corrected.
back_opacity
The window background's opacity (0-255). Values out of range are automatically corrected.
contents_opacity
The opacity of the window's contents (0-255). Values out of range are automatically corrected.
openness (RGSS2)
The openness of the window (from 0 to 255). Values out of range are automatically corrected.
By changing this value from 0 (completely closed) to 255 (completely open), it is possible to create an
animation of the window opening and closing. If the openness is less than 255, the contents of the window
will not be displayed. The default value is 255.
RGSSError
Exception class providing notifications of RGSS internal errors.
Generated when, for instance, trying to access Bitmap or Sprite class objects that have already been freed.
Superclass
{ StandardError
Audio
The module that carries out music and sound processing.
Module Methods
Starts BGM playback. Sets the file name, volume, and pitch in turn.
Also automatically searches files included in RGSS-RTP. File extensions may be omitted.
Audio.bgm_stop
Audio.bgm_fade(time)
Starts BGS playback. Sets the file name, volume, and pitch in turn.
Also automatically searches files included in RGSS-RTP. File extensions may be omitted.
Audio.bgs_stop
Audio.bgs_fade(time)
Starts ME playback. Sets the file name, volume, and pitch in turn.
Also automatically searches files included in RGSS-RTP. File extensions may be omitted.
When ME is playing, the BGM will temporarily stop. The timing of when the BGM restarts is slightly different
from RGSS1. (RGSS2)
Audio.me_stop
Stops ME playback.
Audio.me_fade(time)
Starts SE playback. Sets the file name, volume, and pitch in turn.
Also automatically searches files included in RGSS-RTP. File extensions may be omitted.
When attempting to play the same SE more than once in a very short period, they will automatically be
filtered to prevent choppy playback.
Audio.se_stop
Stops SE playback.
Graphics
The module that carries out graphics processing.
Module Methods
Graphics.update
Refreshes the game screen and advances time by 1 frame. This method must be called at set intervals.
loop do
Graphics.update
Input.update
do_something
end
With RGSS1, if this method was not called for more than 10 seconds, the script was judged to be out of
control and was automatically shut down, but this has been done away with. Even if this method is not called
for a long period of time, Windows messages will still be processed normally, and it is possible to force quit
using Alt + F4 as usual.(RGSS2)
Graphics.wait(duration) (RGSS2)
duration.times do
Graphics.update
end
Graphics.fadeout(duration) (RGSS2)
Graphics.fadein(duration) (RGSS2)
Graphics.freeze
Carries out a transition from the screen fixed in Graphics.freeze to the current screen.
duration is the number of frames the transition will last. When omitted, this value is set to 8.
filename specifies the transition graphic file name. When not specified, a standard fade will be used. Also
automatically searches files included in RGSS-RTP and encrypted archives. File extensions may be omitted.
vague sets the ambiguity of the borderline between the graphic's starting and ending points. The larger the
value, the greater the ambiguity. When omitted, this value is set to 40.
Graphics.snap_to_bitmap (RGSS2)
This reflects the graphics that should be displayed, without relation to use of the freeze method.
Graphics.frame_reset
Resets the screen refresh timing. After a time-consuming process, call this method to prevent extreme frame
skips.
Graphics.width (RGSS2)
Graphics.height (RGSS2)
Module Properties
Graphics.frame_rate
The number of times the screen is refreshed per second. The larger the value, the more CPU power is
required. Normally set at 60. (RGSS2)
Changing this property is not recommended; however, it can be set anywhere from 10 to 120. Values out of
range are automatically corrected.
Graphics.frame_count
The screen's refresh rate count. Set this property to 0 at game start and the game play time (in seconds) can
be calculated by dividing this value by the frame_rate property value.
Graphics.brightness (RGSS2)
The brightness of the screen. Takes a value from 0 to 255. The fadeout, fadein, and transition methods
change this value internally, as required.
Input
A module that handles input data from a gamepad or keyboard.
Module Methods
Input.update
Updates input data. As a rule, this method is called once per frame.
Input.press?(num)
if Input.press?(Input::C)
do_something
end
Input.trigger?(num)
"Pressed again" is seen as time having passed between the button being not pressed and being pressed.
Input.repeat?(num)
Unlike trigger?, takes into account the repeat input of a button being held down continuously.
Input.dir4
Checks the status of the directional buttons, translates the data into a specialized 4-direction input format,
and returns the number pad equivalent (2, 4, 6, 8).
Input.dir8
Checks the status of the directional buttons, translates the data into a specialized 8-direction input format,
and returns the number pad equivalent (1, 2, 3, 4, 6, 7, 8, 9).
Constants
ABCXYZLR
Numbers directly corresponding to the keyboard's SHIFT, CTRL, and ALT keys.
F5 F6 F7 F8 F9
Numbers corresponding to the keyboard's function keys. The other function keys are reserved by the system
and cannot be obtained.
RPG
A module containing RPGVX Data Structures.
{ RPG::Enemy::DropItem
{ RPG::Enemy::Action
{ RPG::Troop
{ RPG::Troop::Member
{ RPG::Troop::Page
{ RPG::Troop::Page::Condition
{ RPG::State
{ RPG::Animation
{ RPG::Animation::Frame
{ RPG::Animation::Timing
{ RPG::CommonEvent
{ RPG::System
{ RPG::System::Vehicle
{ RPG::System::Terms
{ RPG::System::TestBattler
{ RPG::AudioFile
RPG::BGM
RPG::BGS
RPG::ME
RPG::SE
RPG::Map
Data class for maps.
Superclass
{ Object
Attributes
width
height
scroll_type
Scroll type (0: No Loop, 1: Vertical Loop, 2: Horizontal Loop, 3: Both Loop).
autoplay_bgm
bgm
autoplay_bgs
bgs
disable_dashing
encounter_list
encounter_step
parallax_name
parallax_loop_x
parallax_loop_y
parallax_sx
parallax_sy
parallax_show
data
events
Map events. A hash that represents RPG::Event instances as values, using event IDs as the keys.
Definition
module RPG
class Map
def initialize(width, height)
@width = width
@height = height
@scroll_type = 0
@autoplay_bgm = false
@bgm = RPG::AudioFile.new
@autoplay_bgs = false
@bgs = RPG::AudioFile.new("", 80)
@disable_dashing = false
@encounter_list = []
@encounter_step = 30
@parallax_name = ""
@parallax_loop_x = false
@parallax_loop_y = false
@parallax_sx = 0
@parallax_sy = 0
@parallax_show = false
@data = Table.new(width, height, 3)
@events = {}
end
attr_accessor :width
attr_accessor :height
attr_accessor :scroll_type
attr_accessor :autoplay_bgm
attr_accessor :bgm
attr_accessor :autoplay_bgs
attr_accessor :bgs
attr_accessor :disable_dashing
attr_accessor :encounter_list
attr_accessor :encounter_step
attr_accessor :parallax_name
attr_accessor :parallax_loop_x
attr_accessor :parallax_loop_y
attr_accessor :parallax_sx
attr_accessor :parallax_sy
attr_accessor :parallax_show
attr_accessor :data
attr_accessor :events
end
end
RPG::MapInfo
Data class for map information.
Superclass
{ Object
Attributes
name
parent_id
order
expanded
scroll_x
scroll_y
Definition
module RPG
class MapInfo
def initialize
@name = ""
@parent_id = 0
@order = 0
@expanded = false
@scroll_x = 0
@scroll_y = 0
end
attr_accessor :name
attr_accessor :parent_id
attr_accessor :order
attr_accessor :expanded
attr_accessor :scroll_x
attr_accessor :scroll_y
end
end
RPG::Area
Data class for areas.
Superclass
{ Object
Attributes
id
name
map_id
rect
encounter_list
order
Definition
module RPG
class Area
def initialize
@id = 0
@name = ""
@map_id = 0
@rect = Rect.new(0,0,0,0)
@encounter_list = []
@order = 0
end
attr_accessor :id
attr_accessor :name
attr_accessor :map_id
attr_accessor :rect
attr_accessor :encounter_list
attr_accessor :order
end
end
RPG::Event
Data class for map events.
Superclass
{ Object
Referrer
{ RPG::Map
Attributes
id
name
pages
Inner Class
{ RPG::Event::Page
Definition
module RPG
class Event
def initialize(x, y)
@id = 0
@name = ""
@x = x
@y = y
@pages = [RPG::Event::Page.new]
end
attr_accessor :id
attr_accessor :name
attr_accessor :x
attr_accessor :y
attr_accessor :pages
end
end
RPG::Event::Page
Data class for the event page.
Superclass
{ Object
Referrer
{ RPG::Event
Attributes
condition
graphic
move_type
move_speed
move_frequency
move_route
Movement route (RPG::MoveRoute). Referenced only when the movement type is set to Custom.
walk_anime
step_anime
direction_fix
through
priority_type
trigger
Event trigger (0: action button, 1: player touch, 2: event touch, 3: autorun, 4: parallel process).
list
Inner Classes
{ RPG::Event::Page::Condition
{ RPG::Event::Page::Graphic
Definition
module RPG
class Event
class Page
def initialize
@condition = RPG::Event::Page::Condition.new
@graphic = RPG::Event::Page::Graphic.new
@move_type = 0
@move_speed = 3
@move_frequency = 3
@move_route = RPG::MoveRoute.new
@walk_anime = true
@step_anime = false
@direction_fix = false
@through = false
@priority_type = 0
@trigger = 0
@list = [RPG::EventCommand.new]
end
attr_accessor :condition
attr_accessor :graphic
attr_accessor :move_type
attr_accessor :move_speed
attr_accessor :move_frequency
attr_accessor :move_route
attr_accessor :walk_anime
attr_accessor :step_anime
attr_accessor :direction_fix
attr_accessor :through
attr_accessor :priority_type
attr_accessor :trigger
attr_accessor :list
end
end
end
RPG::Event::Page::Condition
Data class for the event page conditions.
Superclass
{ Object
Referrer
{ RPG::Event::Page
Attributes
switch1_valid
switch2_valid
variable_valid
self_switch_valid
item_valid
actor_valid
switch1_id
switch2_id
variable_id
variable_value
If the [Variable] condition is valid, the standard value of that variable (x and greater).
self_switch_ch
If the [Self Switch] condition is valid, the letter of that self switch ("A".."D").
item_id
actor_id
Definition
module RPG
class Event
class Page
class Condition
def initialize
@switch1_valid = false
@switch2_valid = false
@variable_valid = false
@self_switch_valid = false
@item_valid = false
@actor_valid = false
@switch1_id = 1
@switch2_id = 1
@variable_id = 1
@variable_value = 0
@self_switch_ch = "A"
@item_id = 1
@actor_id = 1
end
attr_accessor :switch1_valid
attr_accessor :switch2_valid
attr_accessor :variable_valid
attr_accessor :self_switch_valid
attr_accessor :item_valid
attr_accessor :actor_valid
attr_accessor :switch1_id
attr_accessor :switch2_id
attr_accessor :variable_id
attr_accessor :variable_value
attr_accessor :self_switch_ch
attr_accessor :item_id
attr_accessor :actor_id
end
end
end
end
RPG::Event::Page::Graphic
Data class for the Event page [Graphics].
Superclass
{ Object
Referrer
{ RPG::Event::Page
Attributes
tile_id
The tile ID. If the specified graphic is not a tile, this value is 0.
character_name
character_index
direction
The direction in which the character is facing (2: down, 4: left, 6: right, 8: up).
pattern
Definition
module RPG
class Event
class Page
class Graphic
def initialize
@tile_id = 0
@character_name = ""
@character_index = 0
@direction = 2
@pattern = 0
end
attr_accessor :tile_id
attr_accessor :character_name
attr_accessor :character_index
attr_accessor :direction
attr_accessor :pattern
end
end
end
end
RPG::EventCommand
Data class for the Event command.
Superclass
{ Object
Referrers
{ RPG::Event::Page
{ RPG::Troop::Page
{ RPG::CommonEvent
Attributes
code
indent
The indent depth. Usually 0; the [Conditional Branch] command, among others, adds 1 with every step
deeper.
parameters
Array containing the Move command arguments. The contents vary for each command.
Definition
module RPG
class EventCommand
def initialize(code = 0, indent = 0, parameters = [])
@code = code
@indent = indent
@parameters = parameters
end
attr_accessor :code
attr_accessor :indent
attr_accessor :parameters
end
end
RPG::MoveRoute
Data class for the Move route.
Superclass
{ Object
Referrer
{ RPG::EventPage
Attributes
repeat
skippable
wait
list
Definition
module RPG
class MoveRoute
def initialize
@repeat = true
@skippable = false
@wait = false
@list = [RPG::MoveCommand.new]
end
attr_accessor :repeat
attr_accessor :skippable
attr_accessor :wait
attr_accessor :list
end
end
RPG::MoveCommand
Data class for the Move command.
Superclass
{ Object
Referrer
{ RPG::MoveRoute
Attributes
code
parameters
Array containing the Move command arguments. The contents vary for each command.
Definition
module RPG
class MoveCommand(code = 0, parameters = [])
def initialize
@code = code
@parameters = parameters
end
attr_accessor :code
attr_accessor :parameters
end
end
RPG::Actor
Data class for actors.
Superclass
{ Object
Attributes
id
name
class_id
initial_level
exp_basis
exp_inflation
character_name
character_index
face_name
face_index
parameters
kind indicates the parameter type (0: MaxHP, 1: MaxMP, 2: Attack, 3: Defense, 4: Spirit, 5: Agility).
weapon_id
armor1_id
armor2_id
armor3_id
armor4_id
two_swords_style
fix_equipment
auto_battle
super_guard
pharmacology
critical_bonus
Definition
module RPG
class Actor
def initialize
@id = 0
@name = ""
@class_id = 1
@initial_level = 1
@exp_basis = 25
@exp_inflation = 35
@character_name = ""
@character_index = 0
@face_name = ""
@face_index = 0
@parameters = Table.new(6,100)
for i in 1..99
@parameters[0,i] = 400+i*50
@parameters[1,i] = 80+i*10
@parameters[2,i] = 15+i*5/4
@parameters[3,i] = 15+i*5/4
@parameters[4,i] = 20+i*5/2
@parameters[5,i] = 20+i*5/2
end
@weapon_id = 0
@armor1_id = 0
@armor2_id = 0
@armor3_id = 0
@armor4_id = 0
@two_swords_style = false
@fix_equipment = false
@auto_battle = false
@super_guard = false
@pharmacology = false
@critical_bonus = false
end
attr_accessor :id
attr_accessor :name
attr_accessor :class_id
attr_accessor :initial_level
attr_accessor :exp_basis
attr_accessor :exp_inflation
attr_accessor :character_name
attr_accessor :character_index
attr_accessor :face_name
attr_accessor :face_index
attr_accessor :parameters
attr_accessor :weapon_id
attr_accessor :armor1_id
attr_accessor :armor2_id
attr_accessor :armor3_id
attr_accessor :armor4_id
attr_accessor :two_swords_style
attr_accessor :fix_equipment
attr_accessor :auto_battle
attr_accessor :super_guard
attr_accessor :pharmacology
attr_accessor :critical_bonus
end
end
RPG::Class
Data class for class.
Superclass
{ Object
Attributes
id
name
position
weapon_set
armor_set
element_ranks
Level of elements efficiency. 1-dimensional array using element IDs as subscripts (Table), with 6 levels (0: A,
1: B, 2: C, 3: D, 4: E, 5: F).
state_ranks
Level of states efficiency. 1-dimensional array using status IDs as subscripts (Table), with 6 levels (0: A, 1:
B, 2: C, 3: D, 4: E, 5: F).
learnings
skill_name_valid
skill_name
Inner Class
{ RPG::Class::Learning
Definition
module RPG
class Class
def initialize
@id = 0
@name = ""
@position = 0
@weapon_set = []
@armor_set = []
@element_ranks = Table.new(1)
@state_ranks = Table.new(1)
@learnings = []
@skill_name_valid = false
@skill_name = ""
end
attr_accessor :id
attr_accessor :name
attr_accessor :position
attr_accessor :weapon_set
attr_accessor :armor_set
attr_accessor :element_ranks
attr_accessor :state_ranks
attr_accessor :learnings
attr_accessor :skill_name_valid
attr_accessor :skill_name
end
end
RPG::Class::Learning
Data class for a [Class's Learned] skills.
Superclass
{ Object
Referrer
{ RPG::Class
Attributes
level
Skill level.
skill_id
Definition
module RPG
class Class
class Learning
def initialize
@level = 1
@skill_id = 1
end
attr_accessor :level
attr_accessor :skill_id
end
end
end
RPG::BaseItem
Superclass of Skill, Item, Weapon, and Armor.
Superclass
{ Object
Attributes
id
name
icon_index
description
note
Definition
module RPG
class Item
def initialize
@id = 0
@name = ""
@icon_index = 0
@description = ""
@note = ""
end
attr_accessor :id
attr_accessor :name
attr_accessor :icon_index
attr_accessor :description
attr_accessor :note
end
end
RPG::UsableItem
Superclass of Skill and Item.
Superclass
{ RPG::BaseItem
Attributes
scope
0: None
1: One Enemy
2: All Enemies
3: One Enemy Dual
4: One Random Enemy
5: 2 Random Enemies
6: 3 Random Enemies
7: One Ally
8: All Allies
9: One Ally (Dead)
10: All Allies (Dead)
11: The User
occasion
0: Always
1: Only in Battle
2: Only from the Menu
3: Never
speed
animation_id
common_event_id
base_damage
variance
atk_f
spi_f
physical_attack
damage_to_mp
absorb_damage
ignore_defense
element_set
plus_state_set
minus_state_set
Methods
for_opponent?
Determines whether or not the area of effect is enemies. Returns true if the value of scope is 1, 2, 3, 4, 5, or
6.
for_friend?
Determines whether or not the area of effect is allies. Returns true if the value of scope is 7, 8, 9, 10, or 11.
for_dead_friend?
Determines whether or not the area of effect is downed allies. Returns true if the value of scope is 9 or 10.
for_user?
Determines whether or not the area of effect is the user. Returns true if the value of scope is 11.
for_one?
Determines whether or not the area of effect is one character. Returns true if the value of scope is 1, 3, 4, 7,
9, or 11.
for_two?
Determines whether or not the area of effect is two characters. Returns true if the value of scope is 5.
for_three?
Determines whether or not the area of effect is three characters. Returns true if the value of scope is 6.
for_random?
Determines whether or not the area of effect is random. Returns true if the value of scope is 4, 5, or 6.
for_all?
Determines whether or not the area of effect is everyone. Returns true if the value of scope is 2, 8, or 10.
dual?
Determines whether or not the area of effect is "One Enemy Dual." Returns true if the value of scope is 3.
need_selection?
Determines whether or not selection of the target is required. Returns true if the value of scope is 1, 3, 7, or
9.
battle_ok?
Determines if it may be used on the battle screen. Returns true if the value of occasion is 0 or 1.
menu_ok?
Determines if it may be used on the menu screen. Returns true if the value of occasion is 0 or 2.
Definition
module RPG
class UsableItem < BaseItem
def initialize
super
@scope = 0
@occasion = 0
@speed = 0
@animation_id = 0
@common_event_id = 0
@base_damage = 0
@variance = 20
@atk_f = 0
@spi_f = 0
@physical_attack = false
@damage_to_mp = false
@absorb_damage = false
@ignore_defense = false
@element_set = []
@plus_state_set = []
@minus_state_set = []
end
def for_opponent?
return [1, 2, 3, 4, 5, 6].include?(@scope)
end
def for_friend?
return [7, 8, 9, 10, 11].include?(@scope)
end
def for_dead_friend?
return [9, 10].include?(@scope)
end
def for_user?
return [11].include?(@scope)
end
def for_one?
return [1, 3, 4, 7, 9, 11].include?(@scope)
end
def for_two?
return [5].include?(@scope)
end
def for_three?
return [6].include?(@scope)
end
def for_random?
return [4, 5, 6].include?(@scope)
end
def for_all?
return [2, 8, 10].include?(@scope)
end
def dual?
return [3].include?(@scope)
end
def need_selection?
return [1, 3, 7, 9].include?(@scope)
end
def battle_ok?
return [0, 1].include?(@occasion)
end
def menu_ok?
return [0, 2].include?(@occasion)
end
attr_accessor :scope
attr_accessor :occasion
attr_accessor :speed
attr_accessor :animation_id
attr_accessor :common_event_id
attr_accessor :base_damage
attr_accessor :variance
attr_accessor :atk_f
attr_accessor :spi_f
attr_accessor :physical_attack
attr_accessor :damage_to_mp
attr_accessor :absorb_damage
attr_accessor :ignore_defense
attr_accessor :element_set
attr_accessor :plus_state_set
attr_accessor :minus_state_set
end
end
RPG::Skill
Data class for skills.
Superclass
{ RPG::UsableItem
Attributes
mp_cost
Number of MP consumed.
hit
message1
message2
Definition
module RPG
class Skill < UsableItem
def initialize
super
@scope = 1
@mp_cost = 0
@hit = 100
@message1 = ""
@message2 = ""
end
attr_accessor :mp_cost
attr_accessor :hit
attr_accessor :message1
attr_accessor :message2
end
end
RPG::Item
Data class for items.
Superclass
{ RPG::UsableItem
Attributes
price
consumable
hp_recovery_rate
HP recovery rate.
hp_recovery
HP recovery amount.
mp_recovery_rate
MP recovery rate.
mp_recovery
MP recovery amount.
parameter_type
Parameter affected (0: None, 1: MaxHP, 2: MaxMP, 3: Attack, 4: Defense, 5: Spirit, 6: Agility).
parameter_points
Definition
module RPG
class Item < UsableItem
def initialize
super
@scope = 7
@price = 0
@consumable = true
@hp_recovery_rate = 0
@hp_recovery = 0
@mp_recovery_rate = 0
@mp_recovery = 0
@parameter_type = 0
@parameter_points = 0
end
attr_accessor :price
attr_accessor :consumable
attr_accessor :hp_recovery_rate
attr_accessor :hp_recovery
attr_accessor :mp_recovery_rate
attr_accessor :mp_recovery
attr_accessor :parameter_type
attr_accessor :parameter_points
end
end
RPG::Weapon
Data class for weapons.
Superclass
{ RPG::BaseItem
Attributes
animation_id
price
hit
atk
def
spi
agi
two_handed
fast_attack
dual_attack
critical_bonus
element_set
state_set
Definition
module RPG
class Weapon < BaseItem
def initialize
super
@animation_id = 0
@price = 0
@hit = 95
@atk = 0
@def = 0
@spi = 0
@agi = 0
@two_handed = false
@fast_attack = false
@dual_attack = false
@critical_bonus = false
@element_set = []
@state_set = []
end
attr_accessor :animation_id
attr_accessor :price
attr_accessor :hit
attr_accessor :atk
attr_accessor :def
attr_accessor :spi
attr_accessor :agi
attr_accessor :two_handed
attr_accessor :fast_attack
attr_accessor :dual_attack
attr_accessor :critical_bonus
attr_accessor :element_set
attr_accessor :state_set
end
end
RPG::Armor
Data class for armor.
Superclass
{ RPG::BaseItem
Attributes
kind
price
eva
atk
def
spi
agi
prevent_critical
half_mp_cost
double_exp_gain
auto_hp_recover
element_set
state_set
Definition
module RPG
class Armor < BaseItem
def initialize
super
@kind = 0
@price = 0
@eva = 0
@atk = 0
@def = 0
@spi = 0
@agi = 0
@prevent_critical = false
@half_mp_cost = false
@double_exp_gain = false
@auto_hp_recover = false
@element_set = []
@state_set = []
end
attr_accessor :kind
attr_accessor :price
attr_accessor :eva
attr_accessor :atk
attr_accessor :def
attr_accessor :spi
attr_accessor :agi
attr_accessor :prevent_critical
attr_accessor :half_mp_cost
attr_accessor :double_exp_gain
attr_accessor :auto_hp_recover
attr_accessor :element_set
attr_accessor :state_set
end
end
RPG::Enemy
Data class for enemies.
Superclass
{ Object
Attributes
id
name
battler_name
battler_hue
maxhp
maxmp
atk
def
spi
agi
hit
eva
exp
gold
drop_item1
drop_item2
levitate
has_critical
element_ranks
Level of elements efficiency. 1-dimensional array using element IDs as subscripts (Table), with 6 levels (0: A,
1: B, 2: C, 3: D, 4: E, 5: F).
state_ranks
Level of states efficiency. 1-dimensional array using status IDs as subscripts (Table), with 6 levels (0: A, 1:
B, 2: C, 3: D, 4: E, 5: F).
actions
note
Inner Class
{ RPG::Enemy::DropItem
{ RPG::Enemy::Action
Definition
module RPG
class Enemy
def initialize
@id = 0
@name = ""
@battler_name = ""
@battler_hue = 0
@maxhp = 10
@maxmp = 10
@atk = 10
@def = 10
@spi = 10
@agi = 10
@hit = 95
@eva = 5
@exp = 0
@gold = 0
@drop_item1 = RPG::Enemy::DropItem.new
@drop_item2 = RPG::Enemy::DropItem.new
@levitate = false
@has_critical = false
@element_ranks = Table.new(1)
@state_ranks = Table.new(1)
@actions = [RPG::Enemy::Action.new]
@note = ""
end
attr_accessor :id
attr_accessor :name
attr_accessor :battler_name
attr_accessor :battler_hue
attr_accessor :maxhp
attr_accessor :maxmp
attr_accessor :atk
attr_accessor :def
attr_accessor :spi
attr_accessor :agi
attr_accessor :hit
attr_accessor :eva
attr_accessor :exp
attr_accessor :gold
attr_accessor :drop_item1
attr_accessor :drop_item2
attr_accessor :levitate
attr_accessor :has_critical
attr_accessor :element_ranks
attr_accessor :state_ranks
attr_accessor :actions
attr_accessor :note
end
end
RPG::Enemy::DropItem
Data class for enemy [Drop Item].
Superclass
{ Object
Referrer
{ RPG::Enemy
Attributes
kind
item_id
weapon_id
armor_id
denominator
Definition
module RPG
class Enemy
class DropItem
def initialize
@kind = 0
@item_id = 1
@weapon_id = 1
@armor_id = 1
@denominator = 1
end
attr_accessor :kind
attr_accessor :item_id
attr_accessor :weapon_id
attr_accessor :armor_id
attr_accessor :denominator
end
end
end
RPG::Enemy::Action
Data class for enemy [Actions].
Superclass
{ Object
Referrer
{ RPG::Enemy
Attributes
kind
Type of action.
0: Basic
1: Skill
basic
0: Attack
1: Guard
2: Escape
3: Do Nothing
skill_id
condition_type
0: Always
1: Turn No.
2: HP
3: MP
4: State
5: Party Level
6: Switch
condition_param1
condition_param2
For example, if the condition is [HP], then condition_param1 will be the minimum value and
condition_param2 will be the maximum value.
rating
Methods
skill?
Definition
module RPG
class Enemy
class Action
def initialize
@kind = 0
@basic = 0
@skill_id = 1
@condition_type = 0
@condition_param1 = 0
@condition_param2 = 0
@rating = 5
end
def skill?
return @kind == 1
end
attr_accessor :kind
attr_accessor :basic
attr_accessor :skill_id
attr_accessor :condition_type
attr_accessor :condition_param1
attr_accessor :condition_param2
attr_accessor :rating
end
end
end
RPG::Troop
Data class for troops.
Superclass
{ Object
Attributes
id
Troop ID.
name
Troop name.
members
pages
Inner Classes
{ RPG::Troop::Member
{ RPG::Troop::Page
Definition
module RPG
class Troop
def initialize
@id = 0
@name = ""
@members = []
@pages = [RPG::BattleEventPage.new]
end
attr_accessor :id
attr_accessor :name
attr_accessor :members
attr_accessor :pages
end
end
RPG::Troop::Member
Data class for troop members.
Superclass
{ Object
Referrer
{ RPG::Troop
Attributes
enemy_id
hidden
immortal
Definition
module RPG
class Troop
class Member
def initialize
@enemy_id = 1
@x = 0
@y = 0
@hidden = false
@immortal = false
end
attr_accessor :enemy_id
attr_accessor :x
attr_accessor :y
attr_accessor :hidden
attr_accessor :immortal
end
end
end
RPG::Troop::Page
Data class for battle events (pages).
Superclass
{ Object
Referrer
{ RPG::Troop
Attributes
condition
Condition (RPG::Troop::Page::Condition).
span
list
Inner Class
{ RPG::Troop::Page::Condition
Definition
module RPG
class Troop
class Page
def initialize
@condition = RPG::Troop::Page::Condition.new
@span = 0
@list = [RPG::EventCommand.new]
end
attr_accessor :condition
attr_accessor :span
attr_accessor :list
end
end
end
RPG::Troop::Page::Condition
A database of battle event [Conditions].
Superclass
{ Object
Referrer
{ RPG::Troop::Page
Attributes
turn_ending
Truth value for whether the [When the end of the turn] condition is valid.
turn_valid
enemy_valid
actor_valid
switch_valid
turn_a
turn_b
a and b values specified in the [Turn No.] condition. To be input in the form A + B * X.
enemy_index
enemy_hp
actor_id
actor_hp
switch_id
Definition
module RPG
class Troop
class Page
class Condition
def initialize
@turn_ending = false
@turn_valid = false
@enemy_valid = false
@actor_valid = false
@switch_valid = false
@turn_a = 0
@turn_b = 0
@enemy_index = 0
@enemy_hp = 50
@actor_id = 1
@actor_hp = 50
@switch_id = 1
end
attr_accessor :turn_ending
attr_accessor :turn_valid
attr_accessor :enemy_valid
attr_accessor :actor_valid
attr_accessor :switch_valid
attr_accessor :turn_a
attr_accessor :turn_b
attr_accessor :enemy_index
attr_accessor :enemy_hp
attr_accessor :actor_id
attr_accessor :actor_hp
attr_accessor :switch_id
end
end
end
end
RPG::State
Data class for state.
Superclass
{ Object
Attributes
id
State ID.
name
State name.
icon_index
restriction
Sets restrictions (0: none, 1: can't use magic, 2: always attack enemies, 3: always attack allies, 4: can't
move, 5: can't move or evade).
priority
atk_rate
Attack percentage.
def_rate
Defense percentage.
spi_rate
Spirit percentage.
agi_rate
Agility percentage.
nonresistance
offset_by_opposite
slip_damage
reduce_hit_ratio
battle_only
release_by_damage
hold_turn
auto_release_prob
message1
message2
message3
message4
element_set
state_set
note
Definition
module RPG
class State
def initialize
@id = 0
@name = ""
@icon_index = 0
@restriction = 0
@priority = 5
@atk_rate = 100
@def_rate = 100
@spi_rate = 100
@agi_rate = 100
@nonresistance = false
@offset_by_opposite = false
@slip_damage = false
@reduce_hit_ratio = false
@battle_only = true
@release_by_damage = false
@hold_turn = 0
@auto_release_prob = 0
@message1 = ""
@message2 = ""
@message3 = ""
@message4 = ""
@element_set = []
@state_set = []
@note = ""
end
attr_accessor :id
attr_accessor :name
attr_accessor :icon_index
attr_accessor :restriction
attr_accessor :priority
attr_accessor :atk_rate
attr_accessor :def_rate
attr_accessor :spi_rate
attr_accessor :agi_rate
attr_accessor :nonresistance
attr_accessor :offset_by_opposite
attr_accessor :slip_damage
attr_accessor :reduce_hit_ratio
attr_accessor :battle_only
attr_accessor :release_by_damage
attr_accessor :hold_turn
attr_accessor :auto_release_prob
attr_accessor :message1
attr_accessor :message2
attr_accessor :message3
attr_accessor :message4
attr_accessor :element_set
attr_accessor :state_set
attr_accessor :note
end
end
RPG::Animation
Data class for animation.
Superclass
{ Object
Attributes
id
name
animation1_name
animation1_hue
The adjustment value for the first animation graphic's hue (0..360).
animation2_name
animation2_hue
The adjustment value for the second animation graphic's hue (0..360).
position
frame_max
Number of frames.
frames
timings
Inner Classes
{ RPG::Animation::Frame
{ RPG::Animation::Timing
Definition
module RPG
class Animation
def initialize
@id = 0
@name = ""
@animation1_name = ""
@animation1_hue = 0
@animation2_name = ""
@animation2_hue = 0
@position = 1
@frame_max = 1
@frames = [RPG::Animation::Frame.new]
@timings = []
end
attr_accessor :id
attr_accessor :name
attr_accessor :animation1_name
attr_accessor :animation1_hue
attr_accessor :animation2_name
attr_accessor :animation2_hue
attr_accessor :position
attr_accessor :frame_max
attr_accessor :frames
attr_accessor :timings
end
end
RPG::Animation::Frame
Data class for animation frames.
Superclass
{ Object
Referrer
{ RPG::Animation
Attributes
cell_max
Number of cells. Equivalent to the largest cell number in the frame set.
cell_data
data_index ranges from 0 to 7 and denotes various information about a cell (0: pattern, 1: X-coordinate, 2: Y-
coordinate, 3: zoom level, 4: angle of rotation, 5: horizontal flip, 6: opacity, 7: blending mode). Patterns are 1
less than the number displayed in RPGVX; -1 indicates that that cell is not in use.
Definition
module RPG
class Animation
class Frame
def initialize
@cell_max = 0
@cell_data = Table.new(0, 0)
end
attr_accessor :cell_max
attr_accessor :cell_data
end
end
end
RPG::Animation::Timing
Data class for the timing of an animation's SE and flash effects.
Superclass
{ Object
Referrer
{ RPG::Animation
Attributes
frame
se
flash_scope
flash_color
flash_duration
Flash duration.
Definition
module RPG
class Animation
class Timing
def initialize
@frame = 0
@se = RPG::AudioFile.new("", 80)
@flash_scope = 0
@flash_color = Color.new(255,255,255,255)
@flash_duration = 5
end
attr_accessor :frame
attr_accessor :se
attr_accessor :flash_scope
attr_accessor :flash_color
attr_accessor :flash_duration
end
end
end
RPG::CommonEvent
Data class for common events.
Superclass
{ Object
Attributes
id
name
trigger
switch_id
list
Definition
module RPG
class CommonEvent
def initialize
@id = 0
@name = ""
@trigger = 0
@switch_id = 1
@list = [RPG::EventCommand.new]
end
attr_accessor :id
attr_accessor :name
attr_accessor :trigger
attr_accessor :switch_id
attr_accessor :list
end
end
RPG::System
Data class for the system.
Superclass
{ Object
Attributes
game_title
version_id
Random number used for update checks. Updates changed values every time data is saved in RPGVX.
party_members
elements
Element list. Text array using element IDs as subscripts, with the element in the 0 position being nil.
switches
Switch list. Text array using switch IDs as subscripts, with the element in the 0 position being nil.
variables
Variable list. Text array using variable IDs as subscripts, with the element in the 0 position being nil.
passages
ship
airship
title_bgm
battle_bgm
battle_end_me
gameover_me
sounds
start_map_id
start_x
start_y
terms
Terms (RPG::System::Terms).
test_battlers
test_troop_id
battler_name
battler_hue
The adjustment value for the battler graphic's hue (0..360), for internal use.
edit_map_id
Inner Classes
{ RPG::System::Vechile
{ RPG::System::Terms
{ RPG::System::TestBattler
Definition
module RPG
class System
def initialize
@game_title = ""
@version_id = 0
@party_members = [1]
@elements = [nil, ""]
@switches = [nil, ""]
@variables = [nil, ""]
@passages = Table.new(8192)
@boat = RPG::System::Vehicle.new
@ship = RPG::System::Vehicle.new
@airship = RPG::System::Vehicle.new
@title_bgm = RPG::BGM.new
@battle_bgm = RPG::BGM.new
@battle_end_me = RPG::ME.new
@gameover_me = RPG::ME.new
@sounds = []
20.times { @sounds.push(RPG::AudioFile.new) }
@test_battlers = []
@test_troop_id = 1
@start_map_id = 1
@start_x = 0
@start_y = 0
@terms = RPG::System::Terms.new
@battler_name = ""
@battler_hue = 0
@edit_map_id = 1
end
attr_accessor :game_title
attr_accessor :version_id
attr_accessor :party_members
attr_accessor :elements
attr_accessor :switches
attr_accessor :variables
attr_accessor :passages
attr_accessor :boat
attr_accessor :ship
attr_accessor :airship
attr_accessor :title_bgm
attr_accessor :battle_bgm
attr_accessor :battle_end_me
attr_accessor :gameover_me
attr_accessor :sounds
attr_accessor :test_battlers
attr_accessor :test_troop_id
attr_accessor :start_map_id
attr_accessor :start_x
attr_accessor :start_y
attr_accessor :terms
attr_accessor :battler_name
attr_accessor :battler_hue
attr_accessor :edit_map_id
end
end
RPG::System::Vehicle
Data class for vehicles.
Superclass
{ Object
Referrer
{ RPG::System
Attributes
character_name
character_index
bgm
start_map_id
start_x
start_y
Definition
module RPG
class System
class Vehicle
def initialize
@character_name = ""
@character_index = 0
@bgm = RPG::AudioFile.new
@start_map_id = 0
@start_x = 0
@start_y = 0
end
attr_accessor :character_name
attr_accessor :character_index
attr_accessor :bgm
attr_accessor :start_map_id
attr_accessor :start_x
attr_accessor :start_y
end
end
end
RPG::System::Terms
Data class for terminology.
Superclass
{ Object
Referrer
{ RPG::System
Attributes
level
level_a
hp
hp_a
mp
mp_a
atk
def
spi
agi
weapon
armor1
armor2
armor3
armor4
weapon1
weapon2
attack
skill
guard
item
equip
status
save
game_end
fight
escape
new_game
continue
shutdown
to_title
cancel
gold
Definition
module RPG
class System
class Terms
def initialize
@level = ""
@level_a = ""
@hp = ""
@hp_a = ""
@mp = ""
@mp_a = ""
@atk = ""
@def = ""
@spi = ""
@agi = ""
@weapon = ""
@armor1 = ""
@armor2 = ""
@armor3 = ""
@armor4 = ""
@weapon1 = ""
@weapon2 = ""
@attack = ""
@skill = ""
@guard = ""
@item = ""
@equip = ""
@status = ""
@save = ""
@game_end = ""
@fight = ""
@escape = ""
@new_game = ""
@continue = ""
@shutdown = ""
@to_title = ""
@cancel = ""
@gold = ""
end
attr_accessor :level
attr_accessor :level_a
attr_accessor :hp
attr_accessor :hp_a
attr_accessor :mp
attr_accessor :mp_a
attr_accessor :atk
attr_accessor :def
attr_accessor :spi
attr_accessor :agi
attr_accessor :weapon
attr_accessor :armor1
attr_accessor :armor2
attr_accessor :armor3
attr_accessor :armor4
attr_accessor :weapon1
attr_accessor :weapon2
attr_accessor :attack
attr_accessor :skill
attr_accessor :guard
attr_accessor :item
attr_accessor :equip
attr_accessor :status
attr_accessor :save
attr_accessor :game_end
attr_accessor :fight
attr_accessor :escape
attr_accessor :new_game
attr_accessor :continue
attr_accessor :shutdown
attr_accessor :to_title
attr_accessor :cancel
attr_accessor :gold
end
end
end
RPG::System::TestBattler
Data class for the battlers used in battle tests.
Superclass
{ Object
Referrer
{ RPG::System
Attributes
actor_id
level
weapon_id
armor1_id
armor2_id
armor3_id
armor4_id
Definition
module RPG
class System
class TestBattler
def initialize
@actor_id = 1
@level = 1
@weapon_id = 0
@armor1_id = 0
@armor2_id = 0
@armor3_id = 0
@armor4_id = 0
end
attr_accessor :actor_id
attr_accessor :level
attr_accessor :weapon_id
attr_accessor :armor1_id
attr_accessor :armor2_id
attr_accessor :armor3_id
attr_accessor :armor4_id
end
end
end
RPG::AudioFile
Superclass of BGM, BGS, ME, and SE.
Superclass
{ Object
Attributes
name
volume
The sound's volume (0..100). The default values are 100 for BGM and ME and 80 for BGS and SE.
pitch
Definition
module RPG
class AudioFile
def initialize(name = "", volume = 100, pitch = 100)
@name = name
@volume = volume
@pitch = pitch
end
attr_accessor :name
attr_accessor :volume
attr_accessor :pitch
end
end
RPG::BGM
Data class for BGM. This class has a method to play oneself with Audio module.
Superclass
{ RPG::AudioFile
Referrers
{ RPG::Map
{ RPG::System
{ RPG::System::Vehicle
{ RPG::EventCommand
Class Methods
RPG::BGM.last
Returns BGM (RPG::BGM) that playing now. If no playing BGM, returns nil.
RPG::BGM.stop
RPG::BGM.fade(time)
Method
play
Definition
module RPG
class BGM < AudioFile
@@last = BGM.new
def play
if @name.empty?
Audio.bgm_stop
@@last = BGM.new
else
Audio.bgm_play("Audio/BGM/" + @name, @volume, @pitch)
@@last = self
end
end
def self.stop
Audio.bgm_stop
@@last = BGM.new
end
def self.fade(time)
Audio.bgm_fade(time)
@@last = BGM.new
end
def self.last
@@last
end
end
end
RPG::BGS
Data class for BGS. This class has a method to play oneself with Audio module.
Superclass
{ RPG::AudioFile
Referrers
{ RPG::Map
{ RPG::EventCommand
Class Methods
RPG::BGS.last
Returns BGS (RPG::BGS) that playing now. If no playing BGS, returns nil.
RPG::BGS.stop
RPG::BGS.fade(time)
Method
play
Definition
module RPG
class BGS < AudioFile
@@last = BGS.new
def play
if @name.empty?
Audio.bgs_stop
@@last = BGS.new
else
Audio.bgs_play("Audio/BGS/" + @name, @volume, @pitch)
@@last = self
end
end
def self.stop
Audio.bgs_stop
@@last = BGS.new
end
def self.fade(time)
Audio.bgs_fade(time)
@@last = BGS.new
end
def self.last
@@last
end
end
end
RPG::ME
Data class for ME. This class has a method to play oneself with Audio module.
Superclass
{ RPG::AudioFile
Referrers
{ RPG::System
{ RPG::EventCommand
Class Methods
RPG::ME.stop
Stops ME playback.
RPG::ME.fade(time)
Method
play
Definition
module RPG
class ME < AudioFile
def play
if @name.empty?
Audio.me_stop
else
Audio.me_play("Audio/ME/" + @name, @volume, @pitch)
end
end
def self.stop
Audio.me_stop
end
def self.fade(time)
Audio.me_fade(time)
end
end
end
RPG::SE
Data class for SE. This class has a method to play oneself with Audio module.
Superclass
{ RPG::AudioFile
Referrers
{ RPG::Animation::Timing
{ RPG::System
{ RPG::EventCommand
{ RPG::MoveCommand
Class Methods
RPG::SE.stop
Stops SE playback.
Method
play
Definition
module RPG
class SE < AudioFile
def play
unless @name.empty?
Audio.se_play("Audio/SE/" + @name, @volume, @pitch)
end
end
def self.stop
Audio.se_stop
end
end
end
Appendix
{ Regular Expressions
{ sprintf Format
Regular Expressions
{ Back References
{ Character Class
{ ^
Beginning of line. Match directly before the first character or line feed.
{ $
End of line. Match directly before the end of a character string or line feed.
{ .
Match any single character that excludes a line feed (when working with multi-byte characters, this refers to
one character, not one byte). With the Regular Expression option m (multiple line mode. See the Regular
Expression Literal.), it matches with any character that includes a line feed.
{ \w
{ \W
{ \s
{ \S
{ \d
{ \D
Non-number.
{ \A
Beginning of a Character String. Differently from ^, it does not influence the effectiveness of a line feed.
{ \Z
End of a character string. Matches the front of a line feed if the character string ends at the line feed.
{ \z
End of a character string. Differently from $ or \Z, it does not influence the effectiveness of a line feed.
{ \b
Outside the specified character class it is a language boundary. (Matches between \a and \W.) While in the
specified class it is a back space (0x08).
{ \B
Non-language boundary.
{ \G
Matches (doesn't have a width) the place matched from the previous one (directly after). Matches the front
position only the first time. (Same as \A)
Can use with scan or gsub. Use when you want to make a match after the location that was matched the
time before.
# Takes values from the front of the line three at a time (for as long as the values continue.)
str = "123456 789"
str.scan(/\G\d\d\d/) {|m| p m }
{ []
{ *
Return the expression from directly before more then 0 times. Will try to match for as long as possible.
{ *?
Quantifiers. Return the expression from directly before more then 0 times. (At shortest 1 match)
{ +
Quantifiers. Return the expression from directly before more then 1 time.
{ +?
Quantifiers. Return the expression from directly before more then 1 time. (At shortest 1 match.)
{ {m}
{ {m,}
{ {m,n}
Control the return of a set group (interval quantifier). Return all of the Regular Expressions from directly
before.
m times
more then m times
more then m times, at most n times.
str = "foofoofoo"
p str[/(foo){1}/] # => "foo"
p str[/(foo){2,}/] # => "foofoofoo"
p str[/(foo){1,2}/] # => "foofoo"
{ {m}?
{ {m,}?
{ {m,n}?
Interval Quantifier. Will return the regular expression from each before for
m times
more then m times
more then m times, at most n times.
{ ?
{ ??
Quantifiers. Will return the previous regular expression 1 or 0 times (at least once).
{ |
Alternative.
{ ()
Regular Expression group movement. The character string matched to the regular expression in parenthesis
is remembered for back referencing.
{ \1, \2 ... \n
{ (?# )
{ (?: )
Back Reference without group movement. That is, use a flexible group movement without becoming the
targets \1, \2 (also $1, $2) etc .
/(abc)/ = セ "abc"
p $1
=> "abc"
/(?:abc)/ = セ "abc"
p $1
=> nil
{ (?= )
The
(?=re1)re2
expression is a regular expression that matches a match of both re1 and re2.
The
re1(?=re2)
expression, is a regular expression that continues to the following character string which matches with re2,
called re1.
{ (?! )
Negative Loookahead. Set place depending on the negation of a pattern. (Has not width.)
The
(?!re1)re2
expression, is a regular expression that does not match re1 but does match re2.
#C Identifier (Starts at [A-Za-z_] and continues with the [0-9A-Za-z_] character string.
/\b(?![0-9])\w+\b/
Back References
The regular expression \1 \2 窶ヲ \n is a back reference. It matches the character string matched in the nth
parentheses (Regular Expression ( ) Grouping).
/((foo)bar)\1\2/
/((foo)bar)foobarfoo/
Example:
re = /(foo|bar|baz)\1/
p re = セ 'foofoo' # => 0
p re = セ 'barbar' # => 0
p re = セ 'bazbaz' # => 0
p re = セ 'foobar' # => nil
The parentheses in use must be more to the left than the back reference.
If there is a back reference in the parentheses in use the match will consistently fail. Also, the match will
consistently fail when a single digit back reference has no parenthesis too.
While one can specify a back reference greater then 2 digits, one must be carefull not to confuse it with \nnn
(characters corresponding to the octal nnn) of backslash notation. If a numeric value is 1 digit, it is a back
reference. When establishing more then 2 digits, it will be perceived as 8-bit code if parentheses are not used.
Also, when working with regular expressions it is necessary to start with 0 (such as \01, etc.) when using 1 bit
code in 8 bit. (There is no back reference \0 so it isn't unclear.)
p /\1/ = セ "\1" # => nil # back reference that doesn use parentheses.
p /\01/ = セ "\1" # => 0 8 bit code
p /\11/ = セ "\11" # => 0 8 bit code
Character Class
Regular class [] is a set character class. One character listed inside the [] will be matched.
For example, for /[abc]/ one of "a", "b" or "c" will be matched. You can also write character strings using the "-"
when characters follow the ASCII code order like this: /[a-c]/. Also, if the first character is a ^ character from
outside of the set character string will be matched.
Any 窶録' not at the beginning will be matched with that character. Also, any "-" at the front or end of a line will be
matched with that character.
p /[]/ = セ ""
p /[^]/ = セ "^"
# => invalid regular expression; empty character class: /[^]/
The "]" at the front of a line (or directly after a NOT "^") doesn't mean that the character class is over but is just a
simple "]". It is recommended that this kind of "]" performs a backslash escape.
"^", "-", "]" and "\\" (backslash) can do a backslash escape and make a match with that character.
Inside the [] you can use character string and the same backslash notation, and also the regular expressions \w,
\W, \s, \S, \d, \D (these are short-hand for the character class).
Please pay attention to to the fact that the character classes below can make a match with a line feed character
too according to the negation (the same is true with regular expressions \W and \D.)
sprintf Format
The sprintf format of Ruby is basically the same as that the C language. However, there are some differences
such as, (1) there is no short or long modifier like in C, (2) there is a 2 bit variable indicator (%b), and (3) not all of
the dialects of sprintf (': 3-digit separators) are supported.
%[flag][width][.accuracy]indicator
Flag
There are 5 types of flags: '#', '+', ' ' (space), '-', '0'
With the 2, 8, and 16 bit indicators ('b', 'o', 'x', 'X'), "0b", "0", "0x" and "0X" are added as prefixes.
For floating point numbers ('f', 'e', 'E', 'g' and 'G') always put a "." in the output.
By adding 'g', 'G' to the above there is a left over 0 on the end.
Symbols will be attached to output character strings. A '+' symbol will especially be added to positive
numbers. This only applies to the following numerical value indicators: 'd', 'i', 'b', 'o', 'x', 'X', 'u', 'f', 'e', 'E', 'g'
and 'G'. Also, for 'b', 'o', 'x', 'X', and 'u', a '-' symbol will be added to negative numbers.
Same meaning as a '+' symbol but here, a blank space is used in place of the '+' symbol, meaning positive.
This only applies to the following numerical value indicators: 'd', 'i', 'b', 'o', 'x', 'X', 'u', 'f', 'e', 'E', 'g', 'G'.
If output is right justified, '0' will fill in the left over sections in place of a blank space.
This only applies to the following numerical value indicators: 'd', 'i', 'b', 'o', 'x', 'X', 'u', 'f', 'g', 'G' (It does not
apply to 'e' or 'E').
p sprintf("%010d", 10)
# => "0000000010"
Width
A number string that begins with any number other than 0 is the specified width. Width displays the length of the
character string produced. Contrary to the value of "Precision", which is mentioned later, only the number string of
the width part is produced.
As for width specification, the length of " ", "+", "-", "0b", "0", "0x", "0X", which are presented as "Flags", is also
considered.
Width is a specification of the "minimum necessary width." If the resulting number string goes over the specified
width, width specification is no longer valid.
If width is specified as '*', then the width value is received from an argument.
Precision
A number string that follows a "." shows the precision (when only a "." is displayed, it is the same as ".0").
Precision means the length of a portion of numerical value strings for the following integer indicators: 'd', 'i', 'b', 'o',
'x', 'X', 'u'.
This means the decimal places for the floating point indicator 'f'.
This means the number of significant figures for floating point indicators 'e', 'E', 'g', and 'G'.
For character string indicators 's' and 'p', the portion which goes over the specified number within the argument
character string is cut out. If width and precision values are the same, only the output for that length will be
performed, no matter what argument is being considered.
If '*' is specified as precision, the precision value will be received from the argument.
Indicators
Indicators show argument pattern interpretations. They cannot be abbreviated, and are divided into the following
groups:
Argument values 0-255 are considered together with character codes, then the corresponding characters are
outputted. Argument conversion is attempted with the to_int method for objects other than numerical values,
String, nil, true, and false.
If the argument is not a String object, the to_s method causes the object turned into a character string to be
treated as an argument.
d
i
The argument value is considered as an integer without a symbol, then outputted as a decimal integer.
outputs p 0xffff_ffff.to_s.
printf("%u", n)
b
o
x
X
Integers are outputted as character strings with binary, octal, hexadecimal, and hexadecimal (upper case
letter) expressions.
If the '#' flag is specified, "0b", "0", "0x", "0X" are added to the front.
If the '+' or ' ' flags are not used, ".." (if the '#' flag is used, after "0x" etc.) is added to the front of negative
numbers. This means that characters of the highest-order digit continue infinetely, and negative numbers are
shown in complementary numbers of 2.
f
e
E
g
G
When the exponent is smaller then -4, or higher than the precision, 'g' outputs the same as 'e'. In all other
cases, it outputs the same as 'f'. However, 0 at the end of a decimal fraction is omitted.
Upper case indicators 'E' and 'G' change the output alphabet into upper case letters.
Argument Specification
nth$
Used when you want to change the format according to the situation, but do not want to change the order.
case ENV['LC_TIME']
when /^ja_JP/
fmt = "%1$d エ%2$d ・3$d ・"
else
fmt = "%2$02d/%03$2d/%1$02d"
end
p sprintf(fmt, 1, 4, 22)
=> "04/22/01"