Ruby can be used in an interactive way, or as a standalone program. There is also an interactive help shell, invoked with the command: ri. Some documentation about a Ruby program can be produced with rdoc from specially formatted comments placed into the source code. Ruby can be used in the following three ways:
The command irb invokes an interactive Ruby shell: the Ruby shell has some useful commands as: an "help" command; a "source" command to load Ruby files; "conf" to show the configuration; an "exit"* command and commands to manage subshell, similar to the batch jobs in Unix.
Using the "ruby" command: a file containing a Ruby program can be executed with: "ruby filename.rb".
The ruby command has also optional flags to execute a string of Ruby statements or to apply Ruby statements to an input streams as in the following examples:
ruby -e 'a=1 ; print "a=",a,"..OK\n " ;' ==> a=1...OK
echo "aaaa" | ruby -n -e 'print $_.upcase' ==> AAA
In Unix an executable file beginning with the line: "#!/usr/bin/ruby" can be executed as a shell command.
Ruby is case sensitive .
Blank lines are ignored and multiple blanks are condensed;
"#" is used for comments, extending from the character: "#" up to the end of the line.
A semicolon: ";* , or a newline, is used to separate statements, but incomplete expressions can extend over more lines. The backslash: "\" can be used to escape the final newline character, effectively joining two lines.
Curly braces: "{ }" are used to define a block of statements;
Logical blocks are initiated by different keywords (begin class, def, if, do), but all are terminated by the keyword: "end".
The special keyword: "__END__" , on a line by itself, without leading or trailing spaces, can be used to mark the end of the program in a Ruby file; all after this line is ignored.
Special blocks of lines have specific delimiters:
=begin here an embedded document, with comments or documentation =end BEGIN { here a block of code executed at the beginning of the program } END { here a block of code executed at the end of the program }
Arrays, hashes and strings are basic types: arrays are sequence of heterogeneous objects, represented as comma separated values between square brackets; their elements are obtained bu an integer index between square brackets. Hashes, instead of an integer index have elements obtained by a key, which can be any object, but is usually a number or a string. Hashes are represented by a sequence of a key and a value, separated by an arrow, between curly brackets. Strings are represented as sequences of characters between single or double quotes. Array and hashes will be described in a subsequent section, but some examples are anticipated here:
a=[1,2,3] # creation of an array of three numbers # a[0] is a reference to '1', a[1] to '2' ... b={"a"=>1,"b"=>2} # an hash of two values, using strings as keys. # b["a"] is a reference to '1', b["b"] to '2'
Variables and method names:
names of variables begin with a lowercase letter and are made by an arbitrary number of letters, digits or underscores;
variables are reference to objects, and assignments for numerics and hashes or dictionaries have different effects:
a=1 ; b=a ; a=2 => you have a==2 ; b==1 ; the assignment b=a makes: '2':a new number object a=[1,2,3] ; b=a ; a[1]=0 => the assignment b=a makes only a new reference. You have both 'a' and 'b' changed to:[1, 0, 3] To make a new array you have to use: b=a.dup The same happens for hashes or strings.
Constants:
constants begin with an uppercase letter, are not really constants, can be changed, but Ruby issues a warning when you change a constant.
Class and Module names are references to classes and modules, constant too and capitalized.
Symbols:
symbols are pointers to the internal name table of Ruby; names of symbols have the prefix ":";
they belong to the class "Symbol", and, from Ruby 1.9, have some methods similar to the methods of strings (size, uppercase,swapcase etc.). There are also conversion functions between strings and symbols:
sym=stringa.to_sym # change a string into a symbol stringa=sym.to_s # change a symbol into a string stringa=sym.id2name # change a symbol into a string Symbol.all_symbols # shows all symbols
Symbols are automatically created by Ruby for nearly every object of a program. The method: Symbol.all_symbols return an array of all the defined symbols; id2name, or to_s, returns a string representing a symbol.
Access to objects through symbols is faster; when an object has been defined, a symbol with the corresponding name can be used to refer to the object. Symbols are often used as keys in hashes.
Some characters have special meaning in names:
Character | Usage |
---|---|
@ | first character for private instance variables |
@@ | first characters for class variables |
$ | first character for global variable |
? | last character for names of functions returning a bool (not mandatory) |
! | last character for names of functions modifying an item in place (not mandatory) |
= | last character for names of functions with an usage which mimics an assignment |
: | prefix for symbols |
Ruby has some reserved words, which can't be used for user-defined names:
__ENCODING__ __FILE__ __LINE__ BEGIN END alias and begin break case class def defined? do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield
As in Perl, there are many global variables pre-defined, and also pre-defined constants, some are in the following table.
Constant | Meaning |
---|---|
$0 | name of the Ruby program ( also: $PROGRAM_NAME) |
$* | array with command line options (also: ARGV) |
$" | array of included modules |
$: | path for module searching |
$stderr, $stdout, $stdin | standard I/O streams |
$_ | last read line |
$; | default string separator for the split function |
$, | separator for printed items (default is nil) |
$! | last raised exception |
$@ | backtrace for last raised exception |
$& | for regular expression: matched string |
$` | substring before the match |
$' | substring after the match |
$1...$n | sub-expressions in the match |
$? | status of the last sub-process (contains the Status object) |
ARGV | array of strings with command line options |
ENV | hash of environment variables |
RUBY_DESCRIPTION | description of the Ruby version |
RUBY_PLATFORM | the computer type |
RUBY_VERSION | Ruby version number |
In the ARGV the options are saved as strings, and the first option is in ARGV[0].
Most of these constants can be changed at run-time.
A ruby program, or the interactive session, can include Ruby statements contained in an external file. The statements are executed in the context of the program; variables, classes, functions and constants defined in the file become available to the program, with the exception of local variables, which are never seen outside of the environment in which they are defined (in this case the external file).
The "load" or the "require" statements are used to load a file:
load 'nomefile.rb' # can be also used to load compiled binaries require 'nomefile' # the ".rb" suffix is assumed require_relative 'nomefile' # search path relative to the current directory # not working for the interactive shell.
The "load" statement can also load compiled libraries into Ruby, and needs the file prefix, which can be ".so" or "dll" for binary libraries, ".rb" for Ruby files. The "require" statement loads only Ruby files and doesn't need the file prefix, assuming that it is ".rb" .
The "load" statement can be executed many times to reload the file; instead the "require" statement load the file only once also if called many times; the variable $" contains a list of the files loaded with require.
Files are searched in the current directory and in system-defined directories. The variable $LOAD_PATH contains an array of directories to search for files, $LOAD_PATH can be changed at run-time.
For example, in a Debian 7 system, we have
$LOAD_PATH == ["/usr/local/lib/site_ruby/1.9.1", "/usr/local/lib/site_ruby/1.9.1/x86_64-linux", "/usr/local/lib/site_ruby", "/usr/lib/ruby/vendor_ruby/1.9.1", "/usr/lib/ruby/vendor_ruby/1.9.1/x86_64-linux", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.9.1", "/usr/lib/ruby/1.9.1/x86_64-linux"] to add the current directory: $LOAD_PATH.unshift('./') or: $LOAD_PATH << '.'
The require_relative statement doesn't search in the $LOAD_PATH, but only in the path relative the directory from which the statement is called. require_relative can't be used in the interactive shell.
In Ruby the scope for names can be one of: local, global, instance and class. Names defined out of classes or functions belong to the "main object" scope.
Local variables (those beginning with a lowercase letter) are local to the file class, function or block in which are defined and can't be accessed from the outside. Functions don't see local variables defined out of the function itself. A block can see variables defined in the program before the block.
Ruby programs (or the interactive session) can include Ruby files, with the "load" or "require" statement. These files are executed in the environment of the program, but local variables defined in the file are not seen in the program and vice-versa.
Global variables are accessible in the whole program and the first character of their name is : "$" .
Instance variables are private to a class instance; their names begins with: "@" and they are seen by the methods of the instance. Special methods are needed to access them from the outside of the object. They have to be initialized by methods of the class, not in the body of the class, outside methods.
In the interactive usage, variables prefixed with "@" are instance variable of the "main" object, and seen in functions.
Class variables, defined in a class, are common to all the instances of the class; if defined in an child class can be seen also in the parent. Their names begin with "@@".
The function: "defined?(varname)" return the scope of a defined variable, or "nil" if not defined.
Names beginning with an uppercase letter (capitalized) are reference to constants.
Constants can't be defined into methods.
Constants defined outside classes are in the global scope.
Constants defined into a class or module belong to the class or module. Can be accessed outside the module with the scope operator "::" (i.e.: "Math::PI"), where the name of the module can be also given by an expression.
Constants defined outside modules, classes or in the main program, can be referred to into classes by using the scope operator "::", without the module name ( Es.: ::Constant ).