Ruby Is A Pure Object Oriented Programming Language
Ruby Is A Pure Object Oriented Programming Language
Ruby Is A Pure Object Oriented Programming Language
You can find the name Yukihiro Matsumoto on the Ruby mailing list at www.ruby-lang.org. Matsumoto is also known as Matz in the Ruby community. Ruby is "A Programmer's Best Friend". Ruby has features that are similar to those of Smalltalk, Perl, and Python. Perl, Python, and Smalltalk are scripting languages. Smalltalk is a true object-oriented language. Ruby, like Smalltalk, is a perfect objectoriented language. Using Ruby syntax is much easier than using Smalltalk syntax.
Features of Ruby:
Ruby is an open-source and is freely available on the Web, but it is subject to a license. Ruby is a general-purpose, interpreted programming language. Ruby is a true object-oriented programming language. Ruby is a server-side scripting language similar to Python and PERL. Ruby can be used to write Common Gateway Interface (CGI) scripts. Ruby can be embeded into Hypertext Markup Language (HTML). Ruby has a clean and easy syntax that allows a new developer to learn Ruby very quickly and easily. Ruby has similar syntax to that of many programming languages such as C++ and Perl. Ruby is very much scalable and big programs written in Ruby are easily maintainable. Ruby can be used for developing Internet and intranet applications. Ruby can be installed in Windows and POSIX environments. Ruby support many GUI tools such as Tcl/Tk, GTK, and OpenGL. Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase. Ruby has a rich set of built-in functions which can be used directly into Ruby scripts.
Linux 7.1 or Windows 95/98/2000/NT operating system Apache 1.3.19-5 Web server Internet Explorer 5.0 or above Web browser Ruby 1.6.6
This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Ruby. It also will talk about extending and embedding Ruby applications.
If you are working on Windows machine then you can use any simple text editor like Notepad or Edit plus. VIM (Vi IMproved) is very simple text editor. This is available on almost all Unix machines and now Windows as well. Otherwise your can use your favorite vi editor to write Ruby programs. RubyWin is a Ruby Integrated Development Environment (IDE) for Windows. Ruby Development Environment (RDE) is also very good IDE for windows users.
$irb irb 0.6.1(99/09/16) irb(main):001:0> def hello irb(main):002:1> out = "Hello World" irb(main):003:1> puts out irb(main):004:1> end nil irb(main):005:0> hello Hello World nil irb(main):006:0>
Let us write a simple program in ruby. All ruby files will have extension .rb. So put the following source code in a test.rb file.
$ ruby test.rb
This will produce following result:
Hello, Ruby!
You have seen a simple Ruby program, now lets see few basic concepts related to Ruby Syntax:
a + b is interpreted as a+b ( Here a is a local variable) a +b is interpreted as a(+b) ( Here a is a method call)
Ruby Identifiers:
Identifiers are names of variables, constants, and methods. Ruby identifiers are case sensitive. It mean Ram and RAM are two different itendifiers in Ruby. Ruby identifier names may consist of alphanumeric characters and the underscore character ( _ ).
Reserved Words:
The following list shows the reserved words in Ruby. These reserved words may not be used as constant or variable names. They can, however, be used as method names. BEGIN END alias and begin break case class def defined? do else elsif end ensure false for if in module next nill not or redo rescue retry return self super then true undef unless until when while while __FILE__ __LINE__
#!/usr/bin/ruby -w print <<EOF This is the first way of creating here document ie. multiple line string. EOF print <<"EOF"; # same as above This is the second way of creating here document ie. multiple line string. EOF print <<`EOC` echo hi there echo lo there EOC print <<"foo", <<"bar" I said foo. foo I said bar. bar # execute commands
This is the first way of creating her document ie. multiple line string. This is the second way of creating her document ie. multiple line string. hi there lo there I said foo. I said bar.
Example:
#!/usr/bin/ruby puts "This is main Ruby Program" BEGIN { puts "Initializing Ruby Program" }
Example:
#!/usr/bin/ruby puts "This is main Ruby Program" END { puts "Terminating Ruby Program" } BEGIN { puts "Initializing Ruby Program" }
This will produce following result:
Initializing Ruby Program This is main Ruby Program Terminating Ruby Program
Ruby Comments:
A comment hides a line, part of a line, or several lines from the Ruby interpreter. You can use the hash character (#) at the beginning of a line:
# # # #
This is a comment. This is a comment, too. This is a comment, too. I said that already.
Here is another form. This block comment conceals several lines from the interpreter with =begin/=end:
=begin This is a comment. This is a comment, too. This is a comment, too. I said that already. =end
Ruby is a perfect Object Oriented Programming Language. The features of the object-oriented programming language include:
These features have been discussed in Object Oriented Ruby. An object-oriented program involves classes and objects. A class is the blueprint from which individual objects are created. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. Take the example of any vehicle. It comprises wheels, horsepower, and fuel or gas tank capacity. These characteristics form the data members of the class Vehicle. You can differentiate one vehicle from the other with the help of these characteristics. A vehicle can also have certain functions, such as halting, driving, and speeding. Even these functions form the data members of the class Vehicle. You can, therefore, define a class as a combination of characteristics and functions. A class Vehicle can be defined as:
Class Vehicle { Number no_of_wheels Number horsepower Characters type_of_tank Number Capacity Function speeding { } Function driving { } Function halting { } }
By assigning different values to these data members, you can form several instances of the class Vehicle. For example, an airplane has three wheels, horsepower of 1,000, fuel as the type of tank, and a capacity of 100 liters. In the same way, a car has four wheels, horsepower of 200, gas as the type of tank, and a capacity of 25 litres.
Local Variables: Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more detail about method in subsequent chapter. Local variables begin with a lowercase letter or _. Instance Variables: Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name. Class Variables: Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name. Global Variables: Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($).
Example:
Using the class variable @@no_of_customers, you can determine the number of objects that are being created. This enables in deriving the number of customers.
Here, cust1 and cust2 are the names of two objects. You write the object name followed by the equal to sign (=) after which the class name will follow. Then, the dot operator and the keywordnew will follow.
class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end end
In this example, you declare the initialize method with id, name, and addr as local variables. Here def and end are used to define a Ruby method initialize. You will learn more about methods in subsequent chapters. In the initialize method, you pass on the values of these local variables to the instance variables @cust_id, @cust_name, and @cust_addr. Here local variables hold the values that are passed along with the new method. Now you can create objects as follows:
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala")
Here statement 1 and statement 2 are part of the body of the method function inside the class Sample. These statments could be any valid Ruby statement. For example we can put a methodputs to print Hello Ruby as follows:
#!/usr/bin/ruby class Sample def hello puts "Hello Ruby!" end end # Now using above class to create objects object = Sample. new object.hello
This will produce following result:
Hello Ruby!
Variables are the memory locations which holds any data to be used by any program. There are five types of variables supported by Ruby. You already have gone through a small description of these variables in previous chapter as well. These five types of variables are explained in this chapter.
#!/usr/bin/ruby $global_variable = 10 class Class1 def print_global puts "Global variable in Class1 is #$global_variable" end end
class Class2 def print_global puts "Global variable in Class2 is #$global_variable" end end class1obj = Class1.new class1obj.print_global class2obj = Class2.new class2obj.print_global
Here $global_variable is a global variable. This will produce following result: NOTE: In Ruby you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant.
#!/usr/bin/ruby class Customer def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end end # Create Objects cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala") # Call Methods cust1.display_details() cust2.display_details()
Here @cust_id, @cust_name and @cust_addr are instance variables. This will produce following result:
#!/usr/bin/ruby class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end def total_no_of_customers() @@no_of_customers += 1 puts "Total number of customers: #@@no_of_customers" end end # Create Objects cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala") # Call Methods cust1.total_no_of_customers() cust2.total_no_of_customers()
Here @@no_of_customers is a class variable. This will produce following result:
Assignment to uninitialized local variables also serves as variable declaration. The variables start to exist until the end of the current scope is reached. The lifetime of local variables is determined when Ruby parses the program. In the above example local variables are id, name and addr.
Ruby Constants:
Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning.
#!/usr/bin/ruby class Example VAR1 = 100 VAR2 = 200 def show puts "Value of first Constant is #{VAR1}" puts "Value of second Constant is #{VAR2}" end end # Create Objects object=Example.new() object.show
Here VAR1 and VAR2 are constant. This will produce following result:
Ruby Pseudo-Variables:
They are special variables that have the appearance of local variables but behave like constants. You can not assign any value to these variables.
self: The receiver object of the current method. true: Value representing true. false: Value representing false. nil: Value representing undefined. __FILE__: The name of the current source file. __LINE__: The current line number in the source file.
Integer Numbers:
Ruby supports integer numbers. An integer number can range from -230 to 230-1 or -262 to 262-1. Integers with-in this range are objects of class Fixnum and integers outside this range are stored in objects of class Bignum. You write integers using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string. You can also get the integer value corresponding to an ASCII character or escape sequence by preceding it with a question mark. Example:
# # # # # # # # #
Fixnum decimal Fixnum decimal with underline Negative Fixnum octal hexadecimal binary character code for 'a' code for a newline (0x0a) Bignum
NOTE: Class and Objects are explained in a separate chapter of this tutorial.
Floating Numbers:
Ruby supports integer numbers. They are also numbers but with decimals. Floating-point numbers are objects of class Float and can be any of the following: Example:
# # # #
floating point value scientific notation dot not required sign before exponential
String Literals:
Ruby strings are simply sequences of 8-bit bytes and they are objects of class String. Double-quoted strings allow substitution and backslash notation but single-quoted strings don't allow substitution and allow backslash notation only for \\ and \' Example:
Backslash Notations:
Following is the list of Backslash notations supported by Ruby: Notation \n \r \f \b \a \e \s \nnn \xnn \cx, \C-x \M-x \M-\C-x Newline (0x0a) Carriage return (0x0d) Formfeed (0x0c) Backspace (0x08) Bell (0x07) Escape (0x1b) Space (0x20) Octal notation (n being 0-7) Hexadecimal notation (n being 0-9, a-f, or A-F) Control-x Meta-x (c | 0x80) Meta-Control-x Character represented
\x
Character x
Ruby Arrays:
Literals of Ruby Array are created by placing a comma-separated series of object references between square brackets. A trailing comma is ignored.
Example:
#!/usr/bin/ruby ary = [ "fred", 10, 3.14, "This is a string", "last element", ] ary.each do |i| puts i end
This will produce following result:
Ruby Hashes:
A literal Ruby Hash is created by placing a list of key/value pairs between braces, with either a comma or the sequence => between the key and the value. A trailing comma is ignored.
Example:
#!/usr/bin/ruby hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f } hsh.each do |key, value| print key, " is ", value, "\n" end
This will produce following result:
Ruby Ranges:
A Range represents an interval.a set of values with a start and an end. Ranges may be constructed using the s..e and s...e literals, or with Range.new. Ranges constructed using .. run from the start to the end inclusively. Those created using ... exclude the end value. When used as an iterator, ranges return each value in the sequence. A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1...5) means it includes 1, 2, 3, 4 values.
Example:
#!/usr/bin/ruby (10..15).each do |n| print n, ' ' end
This will produce following result:
10 11 12 13 14 15
Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument. For each operator (+ - * / % ** & | ^ << >> && ||), there is a corresponding form of abbreviated assignment operator (+= -= etc.)
b / a will give 2
Modulus - Divides left hand operand by right hand operand and returns remainder Exponent - Performs exponential (power) calculation on operators
b % a will give 0
**
!=
(a != b) is true.
>
<
Checks if the value of left operand is less than (a < b) is true. the value of right operand, if yes then condition becomes true. Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true.
>=
<=
(a <= b) is true.
<=>
Combined comparison operator. Returns 0 if (a <=> b) returns -1. first operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second. Used to test equality within a when clause of a case statement. True if the receiver and argument have both the same type and equal values. (1...10) === 5 returns true.
===
.eql?
equal?
True if the receiver and argument have the same object id.
+=
c += a is equivalent to c = c + a
-=
c -= a is equivalent to c = c - a
*=
c *= a is equivalent to c = c * a
/=
c /= a is equivalent to c = c / a
%=
c %= a is equivalent to c = c % a
**=
c **= a is equivalent to c = c ** a
a = 10 b = 20 c = 30
may be more quickly declared using parallel assignment:
a, b, c = 10, 20, 30
Parallel assignment is also useful for swapping the values held in two variables:
a, b = b, c
<<
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
>>
or
(a or b) is true.
&&
(a && b) is true.
||
(a || b) is true.
not
Operator ?:
...
Usage 1
defined? variable # True if variable is initialized
For Example:
Usage 2
defined? method_call # True if a method is defined
For Example:
defined? puts
# => "method"
# => nil (bar is not defined here) # => nil (not defined here)
Usage 3
# True if a method exists that can be called with super user defined? super
For Example:
# => "super" (if it can be called) # => nil (if it cannot be)
Usage 4
defined? yield
For Example:
# => "yield" (if there is a block passed) # => nil (if there is no block)
MR_COUNT = 0 module Foo MR_COUNT = 0 ::MR_COUNT = 1 MR_COUNT = 2 end puts MR_COUNT puts Foo::MR_COUNT
Second Example:
# constant defined on main Object class # set global count to 1 # set local count to 2 # this is the global constant # this is the local "Foo" constant
class Inside_one CONST = proc {' in there'} def where_is_my_CONST ::CONST + ' inside one' end end class Inside_two CONST = ' inside two' def where_is_my_CONST CONST end end puts Inside_one.new.where_is_my_CONST puts Inside_two.new.where_is_my_CONST puts Object::CONST + Inside_two::CONST puts Inside_two::CONST + CONST puts Inside_one::CONST puts Inside_one::CONST.call + Inside_two::CONST
*/% +>> << & ^| <= < > >= <=> == === != =~ !~
&& || .. ... ?: = %= { /= -= += |= &= >>= <<= *= &&= ||= **= defined? not or and
Logical 'AND' Logical 'OR' Range (inclusive and exclusive) Ternary if-then-else Assignment
NOTE: Operators with a Yes in the method column are actually methods, and as such may be overridden. Comments are lines of annotation within Ruby code that are ignored at runtime. A single line comment starts with # charcter and they extend from # to the end of the line as follows:
#!/usr/bin/ruby -w puts "Hello, Ruby!"; =begin This is a multiline comment and con spwan as many lines as you like. But =begin and =end should come in the first line only. =end
Make sure trailing comments are far enough from the code that it is easily distinguished. If more than one trailing comment exists in a block, align them. For example:
@counter @siteCounter
# keeps track times page has been hit # keeps track of times all pages have been hit
****************************************************************************** ******
Ruby offers contional structures that are pretty common to modern languages. Here we will explain all the conditional statements and modifiers available in Ruby
Example:
#!/usr/bin/ruby x=1 if x > 2 puts "x elsif x <= puts "x else puts "I end
is greater than 2" 2 and x!=0 is 1" can't guess the number"
x is 1
Ruby if modifier:
Syntax:
code if condition
Executes code if the conditional is true.
Example:
#!/usr/bin/ruby $debug=1 print "debug\n" if $debug
This will produce following result:
debug
Example:
#!/usr/bin/ruby x=1 unless x>2 puts "x is less than 2" else puts "x is greater than 2" end
This will produce following result:
x is less than 2
Example:
#!/usr/bin/ruby $var = 1
print "1 -- Value is set\n" if $var print "2 -- Value is set\n" unless $var $var = false print "3 -- Value is set\n" unless $var
This will produce following result:
case expr0 when expr1, expr2 stmt1 when expr3, expr4 stmt2 else stmt3 end
is basically similar to the following:
_tmp = expr0 if expr1 === _tmp || expr2 === _tmp stmt1 elsif expr3 === _tmp || expr4 === _tmp stmt2 else stmt3 end
Example:
#!/usr/bin/ruby $age = 5 case $age when 0 .. 2 puts "baby" when 3 .. 6 puts "little child" when 7 .. 12 puts "child" when 13 .. 18 puts "youth" else puts "adult" end
This will produce following result:
little child
Loops in Ruby are used to execute the same block of code a specified number of times. This chapter details all the loop statements supported by Ruby.
Example:
#!/usr/bin/ruby $i = 0; $num = 5; while $i < $num do puts("Inside the loop i = #$i" ); $i +=1; end
This will produce following result:
Example:
#!/usr/bin/ruby $i = 0; $num = 5; begin puts("Inside the loop i = #$i" ); $i +=1; end while $i < $num
This will produce following result:
i i i i i
= = = = =
0 1 2 3 4
Example:
#!/usr/bin/ruby
$i = 0; $num = 5; until $i > $num do puts("Inside the loop i = #$i" ); $i +=1; end
This will produce following result:
i i i i i i
= = = = = =
0 1 2 3 4 5
Example:
#!/usr/bin/ruby $i = 0; $num = 5; begin puts("Inside the loop i = #$i" ); $i +=1; end until $i > $num
This will produce following result:
i i i i i i
= = = = = =
0 1 2 3 4 5
Example:
#!/usr/bin/ruby for i in 0..5 puts "Value of local variable is #{i}" end
Here we have defined the range 0..5. The statement for i in 0..5 will allow i to take values in the range from 0 to 5 (including 5).This will produce following result:
of of of of of of
is is is is is is
0 1 2 3 4 5
Example:
#!/usr/bin/ruby (0..5).each do |i| puts "Value of local variable is #{i}" end
This will produce following result:
of of of of of of
is is is is is is
0 1 2 3 4 5
Example:
#!/usr/bin/ruby for i in 0..5 if i > 2 then break end puts "Value of local variable is #{i}" end
This will produce following result:
Example:
#!/usr/bin/ruby for i in 0..5 if i < 2 then next end puts "Value of local variable is #{i}" end
This will produce following result:
of of of of
is is is is
2 3 4 5
Example:
#!/usr/bin/ruby for i in 0..5 if i < 2 then puts "Value of local variable is #{i}" redo end end
This will produce following result and will go in an infinite loop:
begin do_something # exception raised rescue # handles error retry # restart from beginning end
If retry appears in the iterator, the block, or the body of the for expression, restarts the invocation of the iterator call. Arguments to the iterator is re-evaluated.
Example:
#!/usr/bin/ruby
for i in 1..5 retry if i > 2 puts "Value of local variable is #{i}" end
This will produce following result and will go in an infinite loop:
Value of local variable is 1 Value of local variable is 2 Value of local variable is 1 Value of local variable is 2 Value of local variable is 1 Value of local variable is 2 ............................
Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit. Method names should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly. Methods should be defined before calling them otherwise Ruby will raise an exception for undefined method invoking.
Syntax:
def method_name [( [arg [= default]]...[, * arg [, &expr ]])] expr.. end
So you can define a simple method as follows:
method_name
However, when you call a method with parameters, you write the method name along with the parameters, such as:
method_name 25, 30
The most important drawback to using methods with parameters is that you need to remember the number of parameters whenever you call such methods. For example, if a method accepts three parameters and you pass only two, then Ruby displays an error.
Example:
#!/usr/bin/ruby def test(a1="Ruby", a2="Perl") puts "The programming language is #{a1}" puts "The programming language is #{a2}" end test "C", "C++" test
This will produce following result:
is is is is
Syntax:
return [expr[`,' expr...]]
If more than two expressions are given, the array contains these values will be the return value. If no expression given, nil will be the return value.
Example:
return OR return 12 OR return 1,2,3
Have a look at this example:
#!/usr/bin/ruby def test i = 100 j = 200 k = 300 return i, j, k end var = test puts var
This will produce following result:
#!/usr/bin/ruby def sample (*test) puts "The number of parameters is #{test.length}" for i in 0...test.length puts "The parameters are #{test[i]}" end end sample "Zara", "6", "F" sample "Mac", "36", "M", "MCA"
In this code, you have declared a method sample that accepts one parameter test. However, this parameter is a variable parameter. This means that this parameter can take in any number of variables. So above code will produce following result:
number of parameters is 3 parameters are Zara parameters are 6 parameters are F number of parameters is 4 parameters are Mac parameters are 36 parameters are M parameters are MCA
Class Methods:
When a method is defined outside of the class definition, the method is marked as private by default. On the other hand, the methods defined in the class definition are marked as public by default. The default visibility and the private mark of the methods can be changed by public orprivate of the Module. Whenever you want to access a method of a class, you first need to instantiate the class. Then, using the object, you can access any member of the class. Ruby gives you a way to access a method without instantiating a class. Let us see how a class method is declared and accessed:
Accounts.return_date
To access this method, you need not create objects of the class Accounts.
Synatx:
alias method-name method-name alias global-variable-name global-variable-name
Example:
alias foo bar alias $MATCH $&
Here we have defined boo alias for bar and $MATCH is an alias for $&
Synatx:
undef method-name
Example:
To undefine a method called bar do the following:
undef bar
You have seen how Ruby defines methods where you can put number of statements and then you call that method. Similarly Ruby has a concept of Bolck.
A block consists of chunks of code. You assign a name to a block. The code in the block is always enclosed within braces ({}). A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the name test, then you use the function test to invoke this block. You invoke a block by using the yield statement.
Syntax:
block_name{ statement1 statement2 .......... }
Here you will learn to invoke a block by using a simple yield statement. You will also learn to use a yield statement with parameters for invoking a block. You will check the sample code with both types of yield statements.
#!/usr/bin/ruby def test puts "You are in the method" yield puts "You are again back to the method" yield end test {puts "You are in the block"}
This will produce following result:
in the method in the block again back to the method in the block
You also can pass parameters with the yield statement. Here is an example:
#!/usr/bin/ruby def test yield 5 puts "You are in the method test" yield 100 end test {|i| puts "You are in the block #{i}"}
This will produce following result:
You are in the block 5 You are in the method test You are in the block 100
Here the yield statement is written followed by parameters. You can even pass more than one parameter. In the block, you place a variable between two vertical lines (||) to accept the parameters. Therefore, in the preceding code, the yield 5 statement passes the value 5 as a parameter to the test block. Now look at the following statement:
yield a, b
and the block is:
Hello World!
Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.
Modules provide a namespace and prevent name clashes. Modules implement the mixin facility.
Modules define a namespace, a sandbox in which your methods and constants can play without having to worry about being stepped on by other methods and constants.
Syntax:
module Identifier statement1 statement2 ........... end
Module constants are named just like class constants, with an initial uppercase letter. The method definitions look similar, too: module methods are defined just like class methods. As with class methods, you call a module method by preceding its name with the module.s name and a period, and you reference a constant using the module name and two colons.
Example:
#!/usr/bin/ruby # Module defined in trig.rb file module Trig PI = 3.141592654 def Trig.sin(x) # .. end def Trig.cos(x) # .. end end
We can define one more module with same function name but different functionality:
#!/usr/bin/ruby # Module defined in moral.rb file module Moral VERY_BAD = 0 BAD = 1 def Moral.sin(badness) # ... end end
Like class methods, whenever you define a method in a module, you specify the module name followed by a dot and then the method name.
Syntax:
require filename
Here it is not required to give .rb extension along with a file name.
Example:
require 'trig.rb' require 'moral' y = Trig.sin(Trig::PI/4) wrongdoing = Moral.sin(Moral::VERY_BAD)
IMPORTANT: Here both the files contain same function name. So this will result in code ambiguity while including in calling program but modules avoid this code ambiguity and we are able to call appropriate function using module name.
Syntax:
include modulename
If a module is defined in separate file then it is required to include that file using requirestatement before embeding module in a class.
Example:
Consider following module written in Week.rb file.
module Week FIRST_DAY = "Sunday" def Week.weeks_in_month puts "You have four weeks in a month" end def Week.weeks_in_year puts "You have 52 weeks in a year" end end
Now you can include this module in a class as follows:
#!/usr/bin/ruby require "Week" class Decade include Week no_of_yrs=10 def no_of_months puts Week::FIRST_DAY number=10*12 puts number end end d1=Decade.new puts Week::FIRST_DAY Week.weeks_in_month Week.weeks_in_year d1.no_of_months
This will produce following result:
Sunday You have four weeks in a month You have 52 weeks in a year Sunday 120
Mixins in Ruby:
Before going through this section, I assume you have knowledge of Object Oriented Concepts. When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance. Ruby does not suppoprt mutiple inheritance directly but Ruby Modules have another, wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin. Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it. Let us examine the following sample code to gain an understand of mixin:
module def end def end end module def end def end end
A a1 a2 B b1 b2
include B def s1 end end samp=Sample.new samp.a1 samp.a2 samp.b1 samp.b2 samp.s1
Module A consists of the methods a1 and a2. Module B consists of the methods b1 and b2. The class Sample includes both modules A and B. The class Sample can access all four methods, namely, a1, a2, b1, and b2. Therefore, you can see that the class Sample inherits from both the modules. Thus you can say the class Sample shows multiple inheritance or a mixin. A String object in Ruby holds and manipulates an arbitrary sequence of one or more bytes, typically representing characters that represent human language. The simplest string literals are enclosed in single quotes (the apostrophe character). The text within the quote marks is the value of the string:
Expression Substitution:
Expression substitution is a means of embedding the value of any Ruby expression into a string using #{ and }:
#!/usr/bin/ruby x, y, z = puts "The puts "The puts "The 12, 36, 72 value of x is #{ x }." sum of x and y is #{ x + y }." average was #{ (x + y + z)/3 }."
The value of x is 12. The sum of x and y is 48. The average was 40.
%{Ruby is fun.} equivalent to "Ruby is fun." %Q{ Ruby is fun. } equivalent to " Ruby is fun. " %q[Ruby is fun.] equivalent to a single-quoted string %x!ls! equivalent to back tick command output `ls`
Escape Characters:
Following table is a list of escape or non-printable characters that can be represented with backslash notation. NOTE: In a doublequoted string, an escape character is interpreted; in a singlequoted string, an escape character is preserved. Backslash notation \a \b \cx \C-x \e \f \M-\C-x \n \nnn \r \s \t 0x0d 0x20 0x09 0x0a 0x1b 0x0c Hexadecimal character 0x07 0x08 Bell or alert Backspace Control-x Control-x Escape Formfeed Meta-Control-x Newline Octal notation, where n is in the range 0.7 Carriage return Space Tab
Description
\v \x \xnn
0x0b
Vertical tab Character x Hexadecimal notation, where n is in the range 0.9, a.f, or A.F
Character Encoding:
The default character set for Ruby is ASCII, whose characters may be represented by single bytes. If you use UTF-8, or another modern character set, characters may be represented in one to four bytes. You can change your character set using $KCODE at the beginning of your program, like this:
$KCODE = 'u'
Following are the possible values for $KCODE. Code a e n u Description ASCII (same as none). This is the default. EUC. None (same as ASCII). UTF-8.
new [String.new(str="")]
This will returns a new string object containing a copy of str. Now using str object we can all any available instance methods. For example:
this is test
Following are the public String methods ( Assuming str is a String object ): SN 1 Methods with Description str % arg Formats a string using a format specification. arg must be an array if it contains more than one substitution. For information on the format specification. see sprintf under "Kernel Module." str * integer Returns a new string containing integer times str. In other words, str is repeated integer imes. str + other_str Concatenates other_str to str. str << obj Concatenates an object to str. If the object is a Fixnum in the range 0.255, it is converted to a character. Compare it with concat. str <=> other_str Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is casesensitive. str == obj Tests str and obj for equality. If obj is not a String, returns false; returns true if str <=> obj returns 0. str =~ obj Matches str against a regular expression pattern obj. Returns the position where the match starts; otherwise, false. str =~ obj Matches str against a regular expression pattern obj. Returns the position where the match starts; otherwise, false. str.capitalize Capitalizes a string. str.capitalize! Same as capitalize, but changes are made in place.
10
11
str.casecmp Makes a case-insensitive comparison of strings. str.center Centers a string. str.chomp Removes the record separator ($/), usually \n, from the end of a string. If no record separator exists, does nothing. str.chomp! Same as chomp, but changes are made in place. str.chop Removes the last character in str. str.chop! Same as chop, but changes are made in place. str.concat(other_str) Concatenates other_str to str. str.count(str, ...) Counts one or more sets of characters. If there is more than one set of characters, counts the intersection of those sets str.crypt(other_str) Applies a one-way cryptographic hash to str. The argument is the salt string, which should be two characters long, each character in the range a.z, A.Z, 0.9, . or /. str.delete(other_str, ...) Returns a copy of str with all characters in the intersection of its arguments deleted. str.delete!(other_str, ...) Same as delete, but changes are made in place. str.downcase Returns a copy of str with all uppercase letters replaced with lowercase. str.downcase! Same as downcase, but changes are made in place. str.dump Returns a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped.
12
13
14
15
16
17
18
19
20
21
22
23
24
25
str.each(separator=$/) { |substr| block } Splits str using argument as the record separator ($/ by default), passing each substring to the supplied block. str.each_byte { |fixnum| block } Passes each byte from str to the block, returning each byte as a decimal representation of the byte. str.each_line(separator=$/) { |substr| block } Splits str using argument as the record separator ($/ by default), passing each substring to the supplied block. str.empty? Returns true if str is empty (has a zero length). str.eql?(other) Two strings are equal if the have the same length and content. str.gsub(pattern, replacement) [or] str.gsub(pattern) { |match| block } Returns a copy of str with all occurrences of pattern replaced with either replacement or the value of the block. The pattern will typically be a Regexp; if it is a String then no regular expression metacharacters will be interpreted (that is, /\d/ will match a digit, but '\d' will match a backslash followed by a 'd') str[fixnum] [or] str[fixnum,fixnum] [or] str[range] [or] str[regexp] [or] str[regexp, fixnum] [or] str[other_str] References str, using the following arguments: one Fixnum, returns a character code at fixnum; two Fixnums, returns a substring starting at an offset (first fixnum) to length (second fixnum); range, returns a substring in the range; regexp returns portion of matched string; regexp with fixnum, returns matched data at fixnum; other_str returns substring matching other_str. A negative Fixnum starts at end of string with -1. str[fixnum] = fixnum [or] str[fixnum] = new_str [or] str[fixnum, fixnum] = new_str [or] str[range] = aString [or] str[regexp] =new_str [or] str[regexp, fixnum] =new_str [or] str[other_str] = new_str ] Replace (assign) all or part of a string. Synonym of slice!. str.gsub!(pattern, replacement) [or] str.gsub!(pattern) { |match| block } Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed. str.hash Returns a hash based on the string's length and content. str.hex Treats leading characters from str as a string of hexadecimal digits (with an optional sign
26
27
28
29
30
31
32
33
34
35
and an optional 0x) and returns the corresponding number. Zero is returned on error. 36 str.include? other_str [or] str.include? fixnum Returns true if str contains the given string or character. str.index(substring [, offset]) [or] str.index(fixnum [, offset]) [or] str.index(regexp [, offset]) Returns the index of the first occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search. str.insert(index, other_str) Inserts other_str before the character at the given index, modifying str. Negative indices count from the end of the string, and insert after the given character. The intent is to insert a string so that it starts at the given index. str.inspect Returns a printable version of str, with special characters escaped. str.intern [or] str.to_sym Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. str.length Returns the length of str. Compare size. str.ljust(integer, padstr=' ') If integer is greater than the length of str, returns a new String of length integer with str left-justified and padded with padstr; otherwise, returns str. str.lstrip Returns a copy of str with leading whitespace removed. str.lstrip! Removes leading whitespace from str, returning nil if no change was made. str.match(pattern) Converts pattern to a Regexp (if it isn't already one), then invokes its match method on str. str.oct Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number. Returns 0 if the conversion fails. str.replace(other_str)
37
38
39
40
41
42
43
44
45
46
47
Replaces the contents and taintedness of str with the corresponding values in other_str. 48 str.reverse Returns a new string with the characters from str in reverse order. str.reverse! Reverses str in place. str.rindex(substring [, fixnum]) [or] str.rindex(fixnum [, fixnum]) [or] str.rindex(regexp [, fixnum]) Returns the index of the last occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to end the search.characters beyond this point won't be considered. str.rjust(integer, padstr=' ') If integer is greater than the length of str, returns a new String of length integer with str right-justified and padded with padstr; otherwise, returns str. str.rstrip Returns a copy of str with trailing whitespace removed. str.rstrip! Removes trailing whitespace from str, returning nil if no change was made. str.scan(pattern) [or] str.scan(pattern) { |match, ...| block } Both forms iterate through str, matching the pattern (which may be a Regexp or a String). For each match, a result is generated and either added to the result array or passed to the block. If the pattern contains no groups, each individual result consists of the matched string, $&. If the pattern contains groups, each individual result is itself an array containing one entry per group. str.slice(fixnum) [or] str.slice(fixnum, fixnum) [or] str.slice(range) [or] str.slice(regexp) [or] str.slice(regexp, fixnum) [or] str.slice(other_str) See str[fixnum], etc. str.slice!(fixnum) [or] str.slice!(fixnum, fixnum) [or] str.slice!(range) [or] str.slice!(regexp) [or] str.slice!(other_str) Deletes the specified portion from str, and returns the portion deleted. The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment. str.split(pattern=$;, [limit]) Divides str into substrings based on a delimiter, returning an array of these substrings.
49
50
51
52
53
54
55
56
If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored. If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ` were specified. If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed. 57 str.squeeze([other_str]*) Builds a set of characters from the other_str parameter(s) using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character. str.squeeze!([other_str]*) Squeezes str in place, returning either str, or nil if no changes were made. str.strip Returns a copy of str with leading and trailing whitespace removed. str.strip! Removes leading and trailing whitespace from str. Returns nil if str was not altered. str.sub(pattern, replacement) [or] str.sub(pattern) { |match| block } Returns a copy of str with the first occurrence of pattern replaced with either replacement or the value of the block. The pattern will typically be a Regexp; if it is a String then no regular expression metacharacters will be interpreted. str.sub!(pattern, replacement) [or] str.sub!(pattern) { |match| block } Performs the substitutions of String#sub in place, returning str, or nil if no substitutions were performed. str.succ [or] str.next Returns the successor to str. str.succ! [or] str.next! Equivalent to String#succ, but modifies the receiver in place. str.sum(n=16) Returns a basic n-bit checksum of the characters in str, where n is the optional Fixnum parameter, defaulting to 16. The result is simply the sum of the binary value of each
58
59
60
61
62
63
64
65
character in str modulo 2n - 1. This is not a particularly good checksum. 66 str.swapcase Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase. str.swapcase! Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made. str.to_f Returns the result of interpreting leading characters in str as a floating-point number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0.0 is returned. This method never raises an exception. str.to_i(base=10) Returns the result of interpreting leading characters in str as an integer base (base 2, 8, 10, or 16). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. This method never raises an exception. str.to_s [or] str.to_str Returns the receiver. str.tr(from_str, to_str) Returns a copy of str with the characters in from_str replaced by the corresponding characters in to_str. If to_str is shorter than from_str, it is padded with its last character. Both strings may use the c1.c2 notation to denote ranges of characters, and from_str may start with a ^, which denotes all characters except those listed. str.tr!(from_str, to_str) Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made. str.tr_s(from_str, to_str) Processes a copy of str as described under String#tr, then removes duplicate characters in regions that were affected by the translation. str.tr_s!(from_str, to_str) Performs String#tr_s processing on str in place, returning str, or nil if no changes were made. str.unpack(format) Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted. The format string consists of a sequence of singlecharacter directives, summarized in Table 18. Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk (*) will use up all remaining elements. The directives sSiIlL may each be followed by an
67
68
69
70
71
72
73
74
75
underscore (_) to use the underlying platform's native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the format string. 76 str.upcase Returns a copy of str with all lowercase letters replaced with their uppercase counterparts. The operation is locale insensitive.only characters a to z are affected. str.upcase! Changes the contents of str to uppercase, returning nil if no changes are made. str.upto(other_str) { |s| block } Iterates through successive values, starting at str and ending at other_str inclusive, passing each value in turn to the block. The String#succ method is used to generate each value.
77
78
Float
F, f
Float
Float
Treat sizeof(double) characters as a double in network byte order. Treat sizeof(float) characters as a float in network byte order. Extract hex nibbles from each character (most significant bit first) Extract hex nibbles from each character (least significant bit first). Treat sizeof(int) (modified by _) successive characters as an unsigned native integer. Treat sizeof(int) (modified by _) successive characters as a signed native integer. Treat four (modified by _) successive characters as an unsigned native long integer. Treat four (modified by _) successive characters as a signed native long integer. Quoted-printable. Base64-encoded. Treat four characters as an unsigned long in network byte order. Treat two characters as an unsigned short in network byte order. Treat sizeof(char *) characters as a pointer, and return \emph{len} characters from the referenced location. Treat sizeof(char *) characters as a pointer to a nullterminated string. Treat eight characters as an unsigned quad word (64 bits). Treat eight characters as a signed quad word (64 bits).
String
String
String
Integer
Integer
Integer
Integer
M m N
Fixnum
String
String
Q q
Integer Integer
Fixnum
Treat two (different if _ used) successive characters as an unsigned short in native byte order. Treat two (different if _ used) successive characters as a signed short in native byte order. UTF-8 characters as unsigned integers. UU-encoded. Treat four characters as an unsigned long in little-endian byte order. Treat two characters as an unsigned short in little-endian byte order. BER-compressed integer. Skip backward one character. Skip forward one character.
Fixnum
U u V
Fixnum
w X x Z @
Integer
String
With trailing nulls removed up to first null with *. Skip to the offset given by the length argument.
Example:
Try following example to unpack various data.
"abc \0\0abc \0\0".unpack('A6Z6') "abc \0\0".unpack('a3a3') "abc \0abc \0".unpack('Z*Z*') "aa".unpack('b8B8') "aaa".unpack('h2H2c') "\xfe\xff\xfe\xff".unpack('sS') "now=20is".unpack('M*') "whole".unpack('xax2aX2aX1aX2a')
["abc", "abc "] ["abc", " \000\000"] ["abc ", "abc "] ["10000110", "01100001"] ["16", "61", 97] [-2, 65534] ["now is"] ["h", "e", "l", "l", "o"]
Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index. Array indexing starts at 0, as in C or Java. A negative index is assumed relative to the end of the array--that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.
Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, even other Array objects. Ruby arrays are not as rigid as arrays in other languages. Ruby arrays grow automatically while adding elements to them.
Creating Arrays:
There are many ways to create or initialize an array. One way is with the new class method:
names = Array.new
You can set the size of an array at the time of creating array:
names = Array.new(20)
The array names now has a size or length of 20 elements. You can return the size of an array with either the size or length methods:
macmacmacmac
You can also use a block with new, populating each element with what the block evaluates to:
024681012141618
There is another method of Array, []. It works like this:
0123456789
6
Following are the public array methods ( Assuming array is an array object ): SN 1 Methods with Description array & other_array Returns a new array containing elements common to the two arrays, with no duplicates. array * int [or] array * str Returns a new array built by concatenating the int copies of self. With a String argument, equivalent to self.join(str).
array + other_array Returns a new array built by concatenating the two arrays together to produce a third array. array . other_array Returns a new array that is a copy of the original array, removing any items that also appear in other_array. str <=> other_str Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is casesensitive. array | other_array Returns a new array by joining array with other_array, removing duplicates. array << obj Pushes the given object onto the end of array. This expression returns the array itself, so several appends may be chained together. array <=> other_array Returns an integer (-1, 0, or +1) if this array is less than, equal to, or greater than other_array. array == other_array Two arrays are equal if they contain the same number of elements and if each element is equal to (according to Object.==) the corresponding element in the other array. array[index] [or] array[start, length] [or] array[range] [or] array.slice(index) [or] array.slice(start, length) [or] array.slice(range) Returns the element at index, or returns a subarray starting at start and continuing forlength elements, or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). Returns nil if the index (or starting index) is out of range. array[index] = obj [or] array[start, length] = obj or an_array or nil [or] array[range] = obj or an_array or nil Sets the element at index, or replaces a subarray starting at start and continuing forlength elements, or replaces a subarray specified by range. If indices are greater than the current capacity of the array, the array grows automatically. Negative indices will count backward from the end of the array. Inserts elements if length is zero. If nil is used in the second and third form, deletes elements from self. array.abbrev(pattern = nil) Calculates the set of unambiguous abbreviations for the strings in self. If passed a pattern or a string, only the strings matching the pattern or starting with the string are considered.
10
11
12
13
array.assoc(obj) Searches through an array whose elements are also arrays comparing obj with the first element of each contained array using obj.==. Returns the first contained array that matches , or nil if no match is found. array.at(index) Returns the element at index. A negative index counts from the end of self. Returns nil if the index is out of range. array.clear Removes all elements from array. array.collect { |item| block } [or] array.map { |item| block } Invokes block once for each element of self. Creates a new array containing the values returned by the block. array.collect! { |item| block } [or] array.map! { |item| block } Invokes block once for each element of self, replacing the element with the value returned by block. array.compact Returns a copy of self with all nil elements removed. array.compact! Removes nil elements from array. Returns nil if no changes were made. array.concat(other_array) Appends the elements in other_array to self. array.delete(obj) [or] array.delete(obj) { block } Deletes items from self that are equal to obj. If the item is not found, returns nil. If the optional code block is given, returns the result of block if the item is not found. array.delete_at(index) Deletes the element at the specified index, returning that element, or nil if the index is out of range. array.delete_if { |item| block } Deletes every element of self for which block evaluates to true. array.each { |item| block } Calls block once for each element in self, passing that element as a parameter.
14
15
16
17
18
19
20
21
22
23
24
25
array.each_index { |index| block } Same as Array#each, but passes the index of the element instead of the element itself. array.empty? Returns true if the self array contains no elements. array.eql?(other) Returns true if array and other are the same object, or are both arrays with the same content. array.fetch(index) [or] array.fetch(index, default) [or] array.fetch(index) { |index| block } Tries to return the element at position index. If index lies outside the array, the first form throws an IndexError exception, the second form returns default, and the third form returns the value of invoking block, passing in index. Negative values of index count from the end of the array. array.fill(obj) [or] array.fill(obj, start [, length]) [or] array.fill(obj, range) [or] array.fill { |index| block } [or] array.fill(start [, length] ) { |index| block } [or] array.fill(range) { |index| block } The first three forms set the selected elements of self to obj. A start of nil is equivalent to zero. A length of nil is equivalent to self.length. The last three forms fill the array with the value of the block. The block is passed the absolute index of each element to be filled. array.first [or] array.first(n) Returns the first element, or the first n elements, of the array. If the array is empty, the first form returns nil, and the second form returns an empty array. array.flatten Returns a new array that is a one-dimensional flattening of this array (recursively). array.flatten! Flattens array in place. Returns nil if no modifications were made. (array contains no subarrays.) array.frozen? Returns true if array is frozen (or temporarily frozen while being sorted). array.hash Compute a hash-code for array. Two arrays with the same content will have the same hash code
26
27
28
29
30
31
32
33
34
35
array.include?(obj) Returns true if obj is present in self, false otherwise. array.index(obj) Returns the index of the first object in self that is == to obj. Returns nil if no match is found. array.indexes(i1, i2, ... iN) [or] array.indices(i1, i2, ... iN) This methods is deprecated in latest version of Ruby so please use Array#values_at. array.indices(i1, i2, ... iN) [or] array.indexes(i1, i2, ... iN) This methods is deprecated in latest version of Ruby so please use Array#values_at. array.insert(index, obj...) Inserts the given values before the element with the given index (which may be negative). array.inspect Creates a printable version of array. array.join(sep=$,) Returns a string created by converting each element of the array to a string, separated bysep. array.last [or] array.last(n) Returns the last element(s) of self. If array is empty, the first form returns nil. array.length Returns the number of elements in self. May be zero. array.map { |item| block } [or] array.collect { |item| block } Invokes block once for each element of self. Creates a new array containing the values returned by the block. array.map! { |item| block } [or] array.collect! { |item| block } Invokes block once for each element of array, replacing the element with the value returned by block. array.nitems Returns the number of non-nil elements in self. May be zero. array.pack(aTemplateString) Packs the contents of array into a binary sequence according to the directives in
36
37
38
39
40
41
42
43
44
45
46
47
aTemplateString. Directives A, a, and Z may be followed by a count, which gives the width of the resulting field. The remaining directives also may take a count, indicating the number of array elements to convert. If the count is an asterisk (*), all remaining array elements will be converted. Any of the directives sSiIlL may be followed by an underscore (_) to use the underlying platform's native size for the specified type; otherwise, they use a platformindependent size. Spaces are ignored in the template string. ( See templating Table below ) 48 array.pop Removes the last element from array and returns it, or nil if array is empty. array.push(obj, ...) Pushes (appends) the given obj onto the end of this array. This expression returns the array itself, so several appends may be chained together. array.rassoc(key) Searches through the array whose elements are also arrays. Compares key with the second element of each contained array using ==. Returns the first contained array that matches. array.reject { |item| block } Returns a new array containing the items array for which the block is not true. array.reject! { |item| block } Deletes elements from array for which the block evaluates to true, but returns nil if no changes were made. Equivalent to Array#delete_if. array.replace(other_array) Replaces the contents of array with the contents of other_array, truncating or expanding if necessary. array.reverse Returns a new array containing array's elements in reverse order. array.reverse! Reverses array in place. array.reverse_each {|item| block } Same as Array#each, but traverses array in reverse order. array.rindex(obj) Returns the index of the last object in array == to obj. Returns nil if no match is found. array.select {|item| block } Invokes the block passing in successive elements from array, returning an array containing those elements for which the block returns a true value.
49
50
51
52
53
54
55
56
57
58
59
array.shift Returns the first element of self and removes it (shifting all other elements down by one). Returns nil if the array is empty. array.size Returns the length of array (number of elements). Alias for length. array.slice(index) [or] array.slice(start, length) [or] array.slice(range) [or] array[index] [or] array[start, length] [or] array[range] Returns the element at index, or returns a subarray starting at start and continuing forlength elements, or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). Returns nil if the index (or starting index) are out of range. array.slice!(index) [or] array.slice!(start, length) [or] array.slice!(range) Deletes the element(s) given by an index (optionally with a length) or by a range. Returns the deleted object, subarray, or nil if index is out of range. array.sort [or] array.sort { | a,b | block } Returns a new array created by sorting self. array.sort! [or] array.sort! { | a,b | block } Sorts self. array.to_a Returns self. If called on a subclass of Array, converts the receiver to an Array object. array.to_ary Returns self. array.to_s Returns self.join. array.transpose Assumes that self is an array of arrays and transposes the rows and columns. array.uniq Returns a new array by removing duplicate values in array. array.uniq! Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found). array.unshift(obj, ...)
60
61
62
63
64
65
66
67
68
69
70
71
Prepends objects to the front of array, other elements up one. 72 array.values_at(selector,...) Returns an array containing the elements in self corresponding to the given selector (one or more). The selectors may be either integer indices or ranges. array.zip(arg, ...) [or] array.zip(arg, ...){ | arr | block } Converts any arguments to arrays, then merges elements of array with corresponding elements from each argument.
73
H h I i L l M m N n P p Q, q S s U u V v w X
Hex string (high nibble first). Hex string (low nibble first). Unsigned integer. Integer. Unsigned long. Long. Quoted printable, MIME encoding (see RFC 2045). Base64-encoded string. Long, network (big-endian) byte order. Short, network (big-endian) byte order. Pointer to a structure (fixed-length string). Pointer to a null-terminated string. 64-bit number. Unsigned short. Short. UTF-8. UU-encoded string. Long, little-endian byte order. Short, little-endian byte order. BER-compressed integer \fnm. Back up a byte.
x Z
Example:
Try following example to pack various data.
a = [ "a", "b", "c" ] n = [ 65, 66, 67 ] a.pack("A3A3A3") #=> "a b c " a.pack("a3a3a3") #=> "a\000\000b\000\000c\000\000" n.pack("ccc") #=> "ABC"
A Hash is a collection of key-value pairs like this: "employee" => "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order. If you attempt to access a hash with a key that does not exist, the method will return nil
Creating Hashes:
As with arrays, there is a variety of ways to create hashes. You can create an empty hash with the new class method:
months = Hash.new
You can also use new to create a hash with a default value, which is otherwise just nil:
month month
Here is a simple way of creating and accessing Hash keys/values:
#!/usr/bin/ruby H = Hash["a" => 100, "b" => 200] puts "#{H['a']}" puts "#{H['b']}"
This will produce following result:
100 200
You can use any Ruby object as a key or value, even an array, so following example is a valid one:
Hash[[key =>|, value]* ] or Hash.new [or] Hash.new(obj) [or] Hash.new { |hash, key| block }
This will returns a new hash populated with the given objects. Now using created object we can call any available instance methods. For example:
#!/usr/bin/ruby $, = ", " months = Hash.new( "month" ) months = {"1" => "January", "2" => "February"} keys = months.keys puts "#{keys}"
This will produce following result:
1, 2
Following are the public hash methods ( Assuming hash is an array object ):
SN 1
Methods with Description hash == other_hash Tests whether two hashes are equal, based on whether they have the same number of key-value pairs, and whether the key-value pairs match the corresponding pair in each hash. hash.[key] Using a key, references a value from hash. If the key is not found, returns a default value. hash.[key]=value Associates the value given by value with the key given by key. hash.clear Removes all key-value pairs from hash. hash.default(key = nil) Returns the default value for hash, nil if not set by default=. ([] returns a default value if the key does not exist in hash.) hash.default = obj Sets a default value for hash. hash.default_proc Returns a block if hash was created by a block. hash.delete(key) [or] array.delete(key) { |key| block } Deletes a key-value pair from hash by key. If block is used, returns the result of a block if pair is not found. Compare delete_if. hash.delete_if { |key,value| block } Deletes a key-value pair from hash for every pair the block evaluates to true. hash.each { |key,value| block } Iterates over hash, calling the block once for each key, passing the key-value as a twoelement array. hash.each_key { |key| block } Iterates over hash, calling the block once for each key, passing key as a parameter. hash.each_key { |key_value_array| block } Iterates over hash, calling the block once for each key, passing the key and value as parameters.
10
11
12
13
hash.each_key { |value| block } Iterates over hash, calling the block once for each key, passing value as a parameter. hash.empty? Tests whether hash is empty (contains no key-value pairs), returning true or false. hash.fetch(key [, default] ) [or] hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned. hash.has_key?(key) [or] hash.include?(key) [or] hash.key?(key) [or] hash.member?(key) Tests whether a given key is present in hash, returning true or false. hash.has_value?(value) Tests whether hash contains the given value. hash.index(value) Returns the key for the given value in hash, nil if no matching value is found. hash.indexes(keys) Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found. This method is deprecated. Use select. hash.indices(keys) Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found. This method is deprecated. Use select. hash.inspect Returns a pretty print string version of hash. hash.invert Creates a new hash, inverting keys and values from hash; that is, in the new hash, the keys from hash become values, and values become keys. hash.keys Creates a new array with keys from hash. hash.length Returns the size or length of hash as an integer. hash.merge(other_hash) [or] hash.merge(other_hash) { |key, oldval, newval| block } Returns a new hash containing the contents of hash and other_hash, overwriting pairs in
14
15
16
17
18
19
20
21
22
23
24
25
hash with duplicate keys with those from other_hash. 26 hash.merge!(other_hash) [or] hash.merge!(other_hash) { |key, oldval, newval| block } Same as merge, but changes are done in place. hash.rehash Rebuilds hash based on the current values for each key. If values have changed since they were inserted, this method reindexes hash. hash.reject { |key, value| block } Creates a new hash for every pair the block evaluates to true hash.reject! { |key, value| block } Same as reject, but changes are made in place. hash.replace(other_hash) Replaces the contents of hash with the contents of other_ hash. hash.select { |key, value| block } Returns a new array consisting of key-value pairs from hash for which the block returnstrue. hash.shift Removes a key-value pair from hash, returning it as a two-element array. hash.size Returns the size or length of hash as an integer. hash.sort Converts hash to a two-dimensional array containing arrays of key-value pairs, then sorts it as an array. hash.store(key, value) Stores a key-value pair in hash. hash.to_a Creates a two-dimensional array from hash. Each key/value pair is converted to an array, and all these arrays are stored in a containing array. hash.to_hash Returns hash (self). hash.to_s Converts hash to an array, then converts that array to a string.
27
28
29
30
31
32
33
34
35
36
37
38
39
hash.update(other_hash) [or] hash.update(other_hash) {|key, oldval, newval| block} Returns a new hash containing the contents of hash and other_hash, overwriting pairs inhash with duplicate keys with those from other_hash. hash.value?(value) Tests whether hash contains the given value. hash.values Returns a new array containing all the values of hash. hash.values_at(obj, ...) Returns a new array containing the values from hash that are associated with the given key or keys.
40
41
42
The Time class represents dates and times in Ruby. It is a thin layer over the system date and time functionality provided by the operating system. This class may be unable on your system to represent dates before 1970 or after 2038. This tutorial will make you familiar with all the most wanted concepts of date and time.
#!/usr/bin/ruby -w time1 = Time.new puts "Current Time : " + time1.inspect # Time.now is a synonym: time2 = Time.now puts "Current Time : " + time2.inspect
This will produce following result:
Current Time : Mon Jun 02 12:02:39 -0700 2008 Current Time : Mon Jun 02 12:02:39 -0700 2008
# Components of a Time puts "Current Time : " puts time.year # => puts time.month # => puts time.day # => puts time.wday # => puts time.yday # => puts time.hour # => puts time.min # => puts time.sec # => puts time.usec # => puts time.zone # =>
+ time.inspect Year of the date Month of the date (1 to 12) Day of the date (1 to 31 ) 0: Day of week: 0 is Sunday 365: Day of year 23: 24-hour clock 59 59 999999: microseconds "UTC": timezone name
Current Time : Mon Jun 02 12:03:08 -0700 2008 2008 6 2 1 154 12 3 8 247476 UTC
# July 8, 2008 Time.local(2008, 7, 8) # July 8, 2008, 09:10am, local time Time.local(2008, 7, 8, 9, 10) # July 8, 2008, 09:10 UTC Time.utc(2008, 7, 8, 9, 10) # July 8, 2008, 09:10:11 GMT (same as UTC) Time.gm(2008, 7, 8, 9, 10, 11)
Following is the example to get all components in an array in the following format:
[sec,min,hour,day,month,year,wday,yday,isdst,zone]
Try the following:
# Returns number of seconds since epoch time = Time.now.to_i # Convert number of seconds into Time object. Time.at(time) # Returns second since epoch which includes microseconds time = Time.now.to_f
time = Time.new # Here is the interpretation time.zone # => "UTC": return the timezone time.utc_offset # => 0: UTC is 0 seconds offset from UTC time.zone # => "PST" (or whatever your timezone is) time.isdst # => false: If UTC does not have DST. time.utc? # => true: if t is in UTC time zone time.localtime # Convert to local timezone. time.gmtime # Convert back to UTC. time.getlocal # Return a new Time object in local zone time.getutc # Return a new Time object in UTC
%W
Week number of the current year, starting with the first Monday as the first day of the first week (00 to 53). Day of the week (Sunday is 0, 0 to 6). Preferred representation for the date alone, no time. Preferred representation for the time alone, no date. Year without a century (00 to 99). Year with century. Time zone name. Literal % character.
%w %x %X %y %Y %Z %%
Time arithmetic:
You can do simple arithmetic with time as follows:
# # # #
Current time 10 seconds ago. Time - number => Time 10 seconds from now Time + number => Time => 10 Time - Time => number of seconds
****************************************************************************** ******
Ranges occur everywhere: January to December, 0 to 9, lines 50 through 67, and so on. Ruby supports ranges and allows us to use ranges in a variety of ways:
Ranges as Sequences:
The first and perhaps most natural use of ranges is to express a sequence. Sequences have a start point, an end point, and a way to produce successive values in the sequence. Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.
The sequence 1..100 is held as a Range object containing references to two Fixnum objects. If you need to, you can convert a range to a list using the to_a method. Try following example:
#!/usr/bin/ruby $, =", " # Array value separator range1 = (1..10).to_a range2 = ('bar'..'bat').to_a puts "#{range1}" puts "#{range2}"
This will produce following result:
#!/usr/bin/ruby # Assume a range digits = 0..9 puts digits.include?(5) ret = digits.min puts "Min value is #{ret}" ret = digits.max puts "Max value is #{ret}" ret = digits.reject {|i| i < 5 } puts "Rejected values are #{ret}" digits.each do |digit| puts "In Loop #{digit}" end
This will produce following result:
true Min value is 0 Max value is 9 Rejected values are 5, 6, 7, 8, 9 In Loop 0 In Loop 1 In Loop 2 In Loop 3 In Loop 4 In Loop 5 In Loop 6 In Loop 7 In Loop 8 In Loop 9
Ranges as Conditions:
Ranges may also be used as conditional expressions. For example, the following code fragment prints sets of lines from standard input, where the first line in each set contains the word startand the last line the word end.:
#!/usr/bin/ruby score = 70 result = case score when 0..40: "Fail" when 41..60: "Pass" when 61..70: "Pass with Merit" when 71..100: "Pass with Distinction" else "Invalid Score" end puts result
This will produce following result:
Ranges as Intervals:
A final use of the versatile range is as an interval test: seeing if some value falls within the interval represented by the range. This is done using ===, the case equality operator.
#!/usr/bin/ruby if ((1..10) === 5) puts "5 lies in (1..10)" end if (('a'..'j') === 'c') puts "c lies in ('a'..'j')" end if (('a'..'j') === 'z') puts "z lies in ('a'..'j')" end
This will produce following result:
Iterators are nothing but methods supported by collections. Objects that store a group of data members are called collections. In Ruby, arrays and hashes can be termed collections. Iterators return all the elements of a collection, one after the other. We will be discussing two iterators here, each and collect. Let's look at these in detail.
Syntax:
collection.each do |variable| code end
Executes code for each element in collection. Here collection could be an array or a ruby hash.
Example:
#!/usr/bin/ruby ary = [1,2,3,4,5] ary.each do |i| puts i end
This will produce following result:
1 2 3 4 5
You always associate the each iterator with a block. It returns each value of the array, one by one, to the block. The value is stored in the variable i and then displayed on the screen.
Syntax:
collection = collection.collect
The collect method need not always be associated with a block. The collect method returns the entire collection, regardless of whether it is an array or a hash.
Example:
#!/usr/bin/ruby a = [1,2,3,4,5] b = Array.new b = a.collect puts b
This will produce following result:
1 2 3 4 5
NOTE: The collect method is not the right way to do copying between arrays. There is another method called a clone which should be used to copy one array into another array. You normally use the collect method when you want to do something with each of the values to get the new array. For example, this code produces an array b containing 10 times each value in a.
10 20 30 40 50
Ruby provides a whole set of I/O-related methods implemented in the Kernel module. All the I/O methods are derived from the class IO. The class IO provides all the basic methods, such as read, write, gets, puts, readline, getc, andprintf. This chapter will cover all ithe basic I/O functions available in Ruby. For more functions please refere to Ruby Class IO.
The puts statement instructs the program to display the value stored in the variable. This will add a new line at the end of each line it writes.
Example:
#!/usr/bin/ruby val1 val2 puts puts = "This is variable one" = "This is variable two" val1 val2
Example:
The following code shows you how to use the gets statement. This code will prompt the user to enter a value, which will be stored in a variable val and finally will be printed on STDOUT.
Example:
The output of the following code is just the character H:
putc str
This will produce following result:
Example:
#!/usr/bin/ruby print "Hello World" print "Good Morning"
This will produce following result:
Syntax:
aFile = File.new("filename", "mode") # ... process the file aFile.close
Modes r
Description Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode. Read-write mode. The file pointer will be at the beginning of the file. Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
r+ w
w+
a+
#!/usr/bin/ruby aFile = File.new("/var/www/tutorialspoint/ruby/test", "r") if aFile content = aFile.sysread(20) puts content else puts "Unable to open file!" end
This statement will output the first 20 characters of the file. The file pointer will now be placed at the 21st character in the file.
#!/usr/bin/ruby aFile = File.new("/var/www/tutorialspoint/ruby/test", "r+") if aFile aFile.syswrite("ABCDEF") else puts "Unable to open file!" end
This statement will write "ABCDEF" into the file.
#!/usr/bin/ruby aFile = File.new("/var/www/tutorialspoint/ruby/test", "r") if aFile aFile.syswrite("ABCDEF") aFile.each_byte {|ch| putc ch; putc ?. } else puts "Unable to open file!" end
Characters are passed one by one to the variable ch and then displayed on the screen as follows:
T.h.i.s. .i.s. .l.i.n.e. .o.n.e. .T.h.i.s. .i.s. .l.i.n.e. .t.w.o. .T.h.i.s. .i.s. .l.i.n.e. .t.h.r.e.e. .A.n.d. .s.o. .o.n.......
In this code, the variable arr is an array. Each line of the file test will be an element in the array arr. Therefore, arr[0] will contain the first line, whereas arr[1] will contain the second line of the file.
Following is the table which can help you to choose different mask for chmod method:
Mask 0700 0400 0200 0100 0070 0040 0020 0010 0007 0004 0002 0001 4000 2000 1000 rwx mask for owner r for owner w for owner x for owner rwx mask for group r for group w for group x for group rwx mask for other r for other w for other x for other Set user ID on execution Set group ID on execution
Description
File Inquiries:
The following command tests whether a file exists before opening it:
#!/usr/bin/ruby # a directory File::directory?( "/usr/local/bin" ) # => true # a file File::directory?( "file.rb" ) # => false
The following command finds whether the file is readable, writable or executable:
#!/usr/bin/ruby File.readable?( "test.txt" ) # => true File.writable?( "test.txt" ) # => true File.executable?( "test.txt" ) # => false
The following command finds whether the file has zero size or not:
The ftype method identifies the type of the file by returning one of the following: file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown. The following command can be used to find when a file was created, modified, or last accessed :
#!/usr/bin/ruby File::ctime( "test.txt" ) # => Fri May 09 10:06:37 -0700 2008 File::mtime( "text.txt" ) # => Fri May 09 10:44:44 -0700 2008 File::atime( "text.txt" ) # => Fri May 09 10:45:01 -0700 2008
Directories in Ruby:
All files are contained within various directories, and Ruby has no problem handling these too. Whereas the File class handles files, directories are handled with the Dir class.
Dir.chdir("/usr/bin")
You can find out what the current directory is with Dir.pwd:
Dir["/usr/bin/*"]
Creating a Directory:
The Dir.mkdir can be used to create directories:
Dir.mkdir("mynewdir")
You can also set permissions on a new directory (not one that already exists) with mkdir: NOTE: The mask 755 sets permissions owner, group, world [anyone] to rwxr-xr-x where r = read, w = write, and x = execute.
Deleting a Directory:
The Dir.delete can be used to delete a directory. The Dir.unlink and Dir.rmdir perform exactly the same function and are provided for convenience.
Dir.delete("testdir")
require 'tmpdir' tempfilename = File.join(Dir.tmpdir, "tingtong") tempfile = File.new(tempfilename, "w") tempfile.puts "This is a temporary file" tempfile.close File.delete(tempfilename)
This code creates a temporary file, writes data to it, and deletes it. Ruby's standard library also includes a library called Tempfile that can create temporary files for you:
The execution and the exception always go together. If you are opening a file which does not exist then if you did not handle this situation properly then your program is considered to be of bad quality. The program stops if an exception occurs. So exceptions are used to handle various type of errors which may occur during a program execution and take appropriate action instead of halting program completely. Ruby provide a nice mechanism to handle exceptions. We enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.
Syntax :
begin # rescue OneTypeOfException # rescue AnotherTypeOfException # else # Other exceptions ensure # Always will be executed end
Everything from begin to rescue is protected. If an exception occurs during the execution of this block of code, control is passed to the block between rescue and end.
For each rescue clause in the begin block, Ruby compares the raised Exception against each of the parameters in turn. The match will succeed if the exception named in the rescue clause is the same as the type of the currently thrown exception, or is a superclass of that exception. In an event that an exception does not match any of the error types specified, we are allowed to use an else clause after all the rescue clauses.
Example:
#!/usr/bin/ruby begin file = open("/unexistant_file") if file puts "File opened successfully" end rescue file = STDIN end print file, "==", STDIN, "\n"
This will produce following result. You can see that STDIN is substituted to file because openfailed.
#<IO:0xb7d16f84>==#<IO:0xb7d16f84>
Syntax:
begin # Exceptions raised by this code will # be caught by the following rescue clause rescue # This block will capture all types of exceptions retry # This will move control to the beginning of begin end
Example:
#!/usr/bin/ruby begin file = open("/unexistant_file") if file puts "File opened successfully" end rescue fname = "existant_file" retry end
The following is the flow of the process:
an exception occurred at open went to rescue. fname was re-assigned by retry went to the beginning of the begin this time file opens successfully continued the essential process.
NOTE: Notice that if the file of re-substituted name does not exist this example code retries infinitely. Be careful if you use retry for an exception process.
Syntax:
raise OR raise "Error Message" OR raise ExceptionType, "Error Message" OR raise ExceptionType, "Error Message" condition
The first form simply reraises the current exception (or a RuntimeError if there is no current exception). This is used in exception handlers that need to intercept an exception before passing it on. The second form creates a new RuntimeError exception, setting its message to the given string. This exception is then raised up the call stack. The third form uses the first argument to create an exception and then sets the associated message to the second argument. The fourth form is similar to third form but you can add any conditional statement like unless to raise an exception.
Example:
#!/usr/bin/ruby begin puts 'I am before the raise.' raise 'An error has occurred.' puts 'I am after the raise.' rescue puts 'I am rescued.' end puts 'I am after the begin block.'
#!/usr/bin/ruby begin raise 'A test exception.' rescue Exception => e puts e.message puts e.backtrace.inspect end
This will produce following result:
Syntax:
begin #.. process #..raise exception rescue #.. handle error ensure #.. finally ensure execution #.. This will always execute. end
Example:
begin raise 'A test exception.' rescue Exception => e puts e.message puts e.backtrace.inspect ensure puts "Ensuring execution" end
Syntax:
begin #.. process #..raise exception rescue # .. handle error else #.. executes if there is no exception ensure #.. finally ensure execution #.. This will always execute. end
Example:
begin # raise 'A test exception.' puts "I'm not raising exception" rescue Exception => e puts e.message puts e.backtrace.inspect else puts "Congratulations-- no errors!" ensure puts "Ensuring execution" end
This will produce following result:
The catch defines a block that is labeled with the given name (which may be a Symbol or a String). The block is executed normally until a throw is encountered.
Syntax:
throw :lablename #.. this will not be executed catch :lablename do #.. matching catch will be executed after a throw is encountered. end OR throw :lablename condition #.. this will not be executed catch :lablename do #.. matching catch will be executed after a throw is encountered. end
Example:
The following example uses a throw to terminate interaction with the user if '!' is typed in response to any prompt.
def promptAndGet(prompt) print prompt res = readline.chomp throw :quitRequested if res == "!" return res end catch :quitRequested do name = promptAndGet("Name: ") age = promptAndGet("Age: ") sex = promptAndGet("Sex: ") # .. # process information end promptAndGet("Name:")
This will produce following result:
Class Exception:
Ruby's standard classes and modules raise exceptions. All the exception classes form a hierarchy, with the class Exception at the top. The next level contains seven different types:
StandardError SystemExit
There is one other exception at this level, Fatal, but the Ruby interpreter only uses this internally. Both ScriptError and StandardError have a number of subclasses, but we do not need to go into the details here. The important thing is that if we create our own exception classes, they need to be subclasses of either class Exception or one of its descendants. Let's look at an example:
class FileSaveError < StandardError attr_reader :reason def initialize(reason) @reason = reason end end
Now look at the following example which will use this exception:
File.open(path, "w") do |file| begin # Write out the data ... rescue # Something went wrong! raise FileSaveError.new($!) end end
The important line here is raise FileSaveError.new($!). We call raise to signal that an exception has occurred, passing it a new instance of FileSaveError, with the reason being that specific exception caused the writing of the data to fail.
*******************************************************************************