Content
- Enviroment Setup
- Syntax
- Classes and Objects
- Variables, Constants and Literals
- Methods
- Blocks
- Modules and Mixins
- I/O
- Strings
Ruby - Environment Setup
Local Environment Setup
If you are still willing to set up your environment for Ruby programming language, then let's proceed. This tutorial will teach you all the important topics related to environment setup. We would recommend you to go through the following topics first and then proceed further −- Ruby Installation on Linux/Unix − If you are planning to have your development environment on Linux/Unix Machine, then go through this chapter.
- Ruby Installation on Windows − If you are planning to have your development environment on Windows Machine, then go through this chapter.
- Ruby Command Line Options − This chapter list out all the command line options, which you can use along with Ruby interpreter.
- Ruby Environment Variables − This chapter has a list of all the important environment variables to be set to make Ruby Interpreter works.
Popular Ruby Editors
To write your Ruby programs, you will need an editor −- If you are working on Windows machine, then you can use any simple text editor like Notepad or Edit plus.
- VIM (Vi IMproved) is a 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 a very good IDE for windows users.
Interactive Ruby (IRb)
Interactive Ruby (IRb) provides a shell for experimentation. Within the IRb shell, you can immediately view expression results, line by line.This tool comes along with Ruby installation so you have nothing to do extra to have IRb working.
Just type irb at your command prompt and an Interactive Ruby Session will start as given below −
$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>Do not worry about what we did here. You will learn all these steps in subsequent chapters.
What is Next?
We assume now you have a working Ruby Environment and you are ready to write the first Ruby Program. The next chapter will teach you how to write Ruby programs.----------
Ruby - Syntax
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.Live Demo
#!/usr/bin/ruby -w puts "Hello, Ruby!";Here, we assumed that you have Ruby interpreter available in /usr/bin directory. Now, try to run this program as follows −
$ ruby test.rbThis will produce the following result −
Hello, Ruby!You have seen a simple Ruby program, now let us see a few basic concepts related to Ruby Syntax.
Whitespace in Ruby Program
Whitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in strings. Sometimes, however, they are used to interpret ambiguous statements. Interpretations of this sort produce warnings when the -w option is enabled.Example
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)
Line Endings in Ruby Program
Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as +, −, or backslash at the end of a line, they indicate the continuation of a statement.Ruby Identifiers
Identifiers are names of variables, constants, and methods. Ruby identifiers are case sensitive. It means Ram and RAM are two different identifiers 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 | do | next | then |
| END | else | nil | true |
| alias | elsif | not | undef |
| and | end | or | unless |
| begin | ensure | redo | until |
| break | false | rescue | when |
| case | for | retry | while |
| class | if | return | while |
| def | in | self | __FILE__ |
| defined? | module | super | __LINE__ |
Here Document in Ruby
"Here Document" refers to build strings from multiple lines. Following a << you can specify a string or an identifier to terminate the string literal, and all lines following the current line up to the terminator are the value of the string.If the terminator is quoted, the type of quotes determines the type of the line-oriented string literal. Notice there must be no space between << and the terminator.
Here are different examples −
Live Demo
#!/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` # execute commands echo hi there echo lo there EOC print <<"foo", <<"bar" # you can stack them I said foo. foo I said bar. barThis will produce the following result −
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.
Ruby BEGIN Statement
Syntax
BEGIN {
code
}
Declares code to be called before the program is run.Example
Live Demo#!/usr/bin/ruby puts "This is main Ruby Program" BEGIN { puts "Initializing Ruby Program" }This will produce the following result −
Initializing Ruby Program This is main Ruby Program
Ruby END Statement
Syntax
END {
code
}
Declares code to be called at the end of the program.Example
Live Demo#!/usr/bin/ruby puts "This is main Ruby Program" END { puts "Terminating Ruby Program" } BEGIN { puts "Initializing Ruby Program" }This will produce the 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 −# I am a comment. Just ignore me.Or, a comment may be on the same line after a statement or expression −
name = "Madisetti" # This is again commentYou can comment multiple lines as follows −
# 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 - Classes and Objects
Ruby is a perfect Object Oriented Programming Language. The features of the object-oriented programming language include −
- Data Encapsulation
- Data Abstraction
- Polymorphism
- Inheritance
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 liters.
Defining a Class in Ruby
To implement object-oriented programming by using Ruby, you need to first learn how to create objects and classes in Ruby.A class in Ruby always starts with the keyword class followed by the name of the class. The name should always be in initial capitals. The class Customer can be displayed as −
class Customer endYou terminate a class by using the keyword end. All the data members in the class are between the class definition and the end keyword.
Variables in a Ruby Class
Ruby provides four types of variables −- 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 details 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.class Customer @@no_of_customers = 0 end
Creating Objects in Ruby using new Method
Objects are instances of the class. You will now learn how to create objects of a class in Ruby. You can create objects in Ruby by using the method new of the class.The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods.
Here is the example to create two objects cust1 and cust2 of the class Customer −
cust1 = Customer. new cust2 = Customer. newHere, 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 keyword new will follow.
Custom Method to Create Ruby Objects
You can pass parameters to method new and those parameters can be used to initialize class variables.When you plan to declare the new method with parameters, you need to declare the method initialize at the time of the class creation.
The initialize method is a special type of method, which will be executed when the new method of the class is called with parameters.
Here is the example to create initialize method −
class Customer @@no_of_customers = 0 def initialize(id, name, addr) @cust_id = id @cust_name = name @cust_addr = addr end endIn 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")
Member Functions in Ruby Class
In Ruby, functions are called methods. Each method in a class starts with the keyword def followed by the method name.The method name always preferred in lowercase letters. You end a method in Ruby by using the keyword end.
Here is the example to define a Ruby method −
class Sample def function statement 1 statement 2 end endHere, 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 method puts to print Hello Ruby as follows −
class Sample def hello puts "Hello Ruby!" end endNow in the following example, create one object of Sample class and call hello method and see the result −
Live Demo
#!/usr/bin/ruby class Sample def hello puts "Hello Ruby!" end end # Now using above class to create objects object = Sample. new object.helloThis will produce the following result −
Hello Ruby!
Simple Case Study
Here is a case study if you want to do more practice with class and objects.Ruby Class Case Study
----------------
Ruby - Variables, Constants and Literals
Variables are the memory locations, which hold 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 the previous chapter as well. These five types of variables are explained in this chapter.
Ruby Global Variables
Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with the -w option.Assignment to global variables alters the global status. It is not recommended to use global variables. They make programs cryptic.
Here is an example showing the usage of global variable.
Live Demo
#!/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_globalHere $global_variable is a global variable. This will produce the 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.
Global variable in Class1 is 10 Global variable in Class2 is 10
Ruby Instance Variables
Instance variables begin with @. Uninitialized instance variables have the value nil and produce warnings with the -w option.Here is an example showing the usage of Instance Variables.
Live Demo
#!/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 the following result −
Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya Customer id 2 Customer name Poul Customer address New Empire road, Khandala
Ruby Class Variables
Class variables begin with @@ and must be initialized before they can be used in method definitions.Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
Overriding class variables produce warnings with the -w option.
Here is an example showing the usage of class variable −
Live Demo
#!/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 the following result −
Total number of customers: 1 Total number of customers: 2
Ruby Local Variables
Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block's opening brace to its close brace {}.When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments.
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.
Live Demo
#!/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.showHere VAR1 and VAR2 are constants. This will produce the following result −
Value of first Constant is 100 Value of second Constant is 200
Ruby Pseudo-Variables
They are special variables that have the appearance of local variables but behave like constants. You cannot 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.
Ruby Basic Literals
The rules Ruby uses for literals are simple and intuitive. This section explains all basic Ruby Literals.Integer Numbers
Ruby supports integer numbers. An integer number can range from -230 to 230-1 or -262 to 262-1. Integers within 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 the sequence by preceding it with a question mark.
Example
123 # Fixnum decimal 1_234 # Fixnum decimal with underline -500 # Negative Fixnum 0377 # octal 0xff # hexadecimal 0b1011 # binary ?a # character code for 'a' ?\n # code for a newline (0x0a) 12345678901234567890 # BignumNOTE − 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
123.4 # floating point value 1.0e6 # scientific notation 4E20 # dot not required 4e+20 # 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
Live Demo#!/usr/bin/ruby -w puts 'escape using "\\"'; puts 'That\'s right';This will produce the following result −
escape using "\" That's rightYou can substitute the value of any Ruby expression into a string using the sequence #{ expr }. Here, expr could be any ruby expression.
Live Demo
#!/usr/bin/ruby -w puts "Multiplication Value : #{24*60*60}";This will produce the following result −
Multiplication Value : 86400
Backslash Notations
Following is the list of Backslash notations supported by Ruby −| Notation | Character represented |
|---|---|
| \n | Newline (0x0a) |
| \r | Carriage return (0x0d) |
| \f | Formfeed (0x0c) |
| \b | Backspace (0x08) |
| \a | Bell (0x07) |
| \e | Escape (0x1b) |
| \s | Space (0x20) |
| \nnn | Octal notation (n being 0-7) |
| \xnn | Hexadecimal notation (n being 0-9, a-f, or A-F) |
| \cx, \C-x | Control-x |
| \M-x | Meta-x (c | 0x80) |
| \M-\C-x | Meta-Control-x |
| \x | Character x |
Ruby Arrays
Literals of Ruby Array are created by placing a comma-separated series of object references between the square brackets. A trailing comma is ignored.Example
Live Demo#!/usr/bin/ruby ary = [ "fred", 10, 3.14, "This is a string", "last element", ] ary.each do |i| puts i endThis will produce the following result −
fred 10 3.14 This is a string last elementFor more detail on Ruby Arrays, go through Ruby Arrays.
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
Live Demo#!/usr/bin/ruby hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f } hsh.each do |key, value| print key, " is ", value, "\n" endThis will produce the following result −
red is 3840 green is 240 blue is 15For more detail on Ruby Hashes, go through Ruby Hashes.
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
Live Demo#!/usr/bin/ruby (10..15).each do |n| print n, ' ' endThis will produce the following result −
10 11 12 13 14 15For more detail on Ruby Ranges, go through Ruby Ranges.
-------------
Ruby - Methods
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.. endSo, you can define a simple method as follows −
def method_name expr.. endYou can represent a method that accepts parameters like this −
def method_name (var1, var2) expr.. endYou can set default values for the parameters, which will be used if method is called without passing the required parameters −
def method_name (var1 = value1, var2 = value2) expr.. endWhenever you call the simple method, you write only the method name as follows −
method_nameHowever, when you call a method with parameters, you write the method name along with the parameters, such as −
method_name 25, 30The 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
Live Demo#!/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++" testThis will produce the following result −
The programming language is C The programming language is C++ The programming language is Ruby The programming language is Perl
Return Values from Methods
Every method in Ruby returns a value by default. This returned value will be the value of the last statement. For example −def test i = 100 j = 10 k = 0 endThis method, when called, will return the last declared variable k.
Ruby return Statement
The return statement in ruby is used to return one or more values from a Ruby Method.Syntax
return [expr[`,' expr...]]If more than two expressions are given, the array containing 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,3Have a look at this example −
Live Demo
#!/usr/bin/ruby def test i = 100 j = 200 k = 300 return i, j, k end var = test puts varThis will produce the following result −
100 200 300
Variable Number of Parameters
Suppose you declare a method that takes two parameters, whenever you call this method, you need to pass two parameters along with it.However, Ruby allows you to declare methods that work with a variable number of parameters. Let us examine a sample of this −
Live Demo
#!/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, the above code will produce the following result −
The number of parameters is 3 The parameters are Zara The parameters are 6 The parameters are F The number of parameters is 4 The parameters are Mac The parameters are 36 The parameters are M The 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 or private 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 −
class Accounts def reading_charge end def Accounts.return_date end endSee how the method return_date is declared. It is declared with the class name followed by a period, which is followed by the name of the method. You can access this class method directly as follows −
Accounts.return_dateTo access this method, you need not create objects of the class Accounts.
Ruby alias Statement
This gives alias to methods or global variables. Aliases cannot be defined within the method body. The alias of the method keeps the current definition of the method, even when methods are overridden.Making aliases for the numbered global variables ($1, $2,...) is prohibited. Overriding the built-in global variables may cause serious problems.
Syntax
alias method-name method-name alias global-variable-name global-variable-name
Example
alias foo bar alias $MATCH $&Here we have defined foo alias for bar, and $MATCH is an alias for $&
Ruby undef Statement
This cancels the method definition. An undef cannot appear in the method body.By using undef and alias, the interface of the class can be modified independently from the superclass, but notice it may be broke programs by the internal method call to self.
Syntax
undef method-name
Example
To undefine a method called bar do the following −undef bar
-------------
Ruby - Blocks
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 Block.- 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.The yield Statement
Let's look at an example of the yield statement −Live Demo #!/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 the following result −
You are in the method You are in the block You are again back to the method You are in the block You also can pass parameters with the yield statement. Here is an example −
Live Demo #!/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 the 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 −
test {|i| puts "You are in the block #{i}"} Here, the value 5 is received in the variable i. Now, observe the following puts statement −
puts "You are in the block #{i}" The output of this puts statement is −
You are in the block 5 If you want to pass more than one parameters, then the yield statement becomes −
yield a, b and the block is −
test {|a, b| statement} The parameters will be separated by commas.
Blocks and Methods
You have seen how a block and a method can be associated with each other. You normally invoke a block by using the yield statement from a method that has the same name as that of the block. Therefore, you write −Live Demo #!/usr/bin/ruby def test yield end test{ puts "Hello world"} This example is the simplest way to implement a block. You call the test block by using the yield statement.
But if the last argument of a method is preceded by &, then you can pass a block to this method and this block will be assigned to the last parameter. In case both * and & are present in the argument list, & should come later.
Live Demo #!/usr/bin/ruby def test(&block) block.call end test { puts "Hello World!"} This will produce the following result −
Hello World!
BEGIN and END Blocks
Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks).Live Demo #!/usr/bin/ruby BEGIN { # BEGIN block code puts "BEGIN code block" } END { # END block code puts "END code block" } # MAIN block code puts "MAIN code block" A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order. When executed, the above program produces the following result −
BEGIN code block MAIN code block END code block
---------------
Ruby - Modules and Mixins
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.
Syntax
module Identifier statement1 statement2 ........... endModule 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 endWe can define one more module with the 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 endLike class methods, whenever you define a method in a module, you specify the module name followed by a dot and then the method name.
Ruby require Statement
The require statement is similar to the include statement of C and C++ and the import statement of Java. If a third program wants to use any defined module, it can simply load the module files using the Ruby require statement −Syntax
require filenameHere, it is not required to give .rb extension along with a file name.
Example
$LOAD_PATH << '.' require 'trig.rb' require 'moral' y = Trig.sin(Trig::PI/4) wrongdoing = Moral.sin(Moral::VERY_BAD)Here we are using $LOAD_PATH << '.' to make Ruby aware that included files must be searched in the current directory. If you do not want to use $LOAD_PATH then you can use require_relative to include files from a relative directory.
IMPORTANT − Here, both the files contain the 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.
Ruby include Statement
You can embed a module in a class. To embed a module in a class, you use the include statement in the class −Syntax
include modulenameIf a module is defined in a separate file, then it is required to include that file using require statement before embedding module in a class.
Example
Consider the following module written in support.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 endNow, you can include this module in a class as follows −
#!/usr/bin/ruby $LOAD_PATH << '.' require "support" 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_monthsThis will produce the 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, we assume you have the 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 support multiple 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 A def a1 end def a2 end end module B def b1 end def b2 end end class Sample include A include B def s1 end end samp = Sample.new samp.a1 samp.a2 samp.b1 samp.b2 samp.s1Module 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.
--------------
Ruby - I/O
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, and printf.
This chapter will cover all the basic I/O functions available in Ruby. For more functions, please refer to Ruby Class IO.
The puts Statement
In the previous chapters, you have assigned values to variables and then printed the output using puts statement.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
Live Demo#!/usr/bin/ruby val1 = "This is variable one" val2 = "This is variable two" puts val1 puts val2This will produce the following result −
This is variable one This is variable two
The gets Statement
The gets statement can be used to take any input from the user from standard screen called STDIN.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.#!/usr/bin/ruby puts "Enter a value :" val = gets puts valThis will produce the following result −
Enter a value : This is entered value This is entered value
The putc Statement
Unlike the puts statement, which outputs the entire string onto the screen, the putc statement can be used to output one character at a time.Example
The output of the following code is just the character H −Live Demo
#!/usr/bin/ruby str = "Hello Ruby!" putc strThis will produce the following result −
H
The print Statement
The print statement is similar to the puts statement. The only difference is that the puts statement goes to the next line after printing the contents, whereas with the print statement the cursor is positioned on the same line.Example
Live Demo#!/usr/bin/ruby print "Hello World" print "Good Morning"This will produce the following result −
Hello WorldGood Morning
---------------
Ruby - Strings
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 −
'This is a simple Ruby string literal' If you need to place an apostrophe within a single-quoted string literal, precede it with a backslash, so that the Ruby interpreter does not think that it terminates the string −
'Won\'t you read O\'Reilly\'s book?' The backslash also works to escape another backslash, so that the second backslash is not itself interpreted as an escape character.
Following are the string-related features of Ruby.
Expression Substitution
Expression substitution is a means of embedding the value of any Ruby expression into a string using #{ and } −Live Demo #!/usr/bin/ruby x, y, z = 12, 36, 72 puts "The value of x is #{ x }." puts "The sum of x and y is #{ x + y }." puts "The average was #{ (x + y + z)/3 }." This will produce the following result −
The value of x is 12. The sum of x and y is 48. The average was 40.
General Delimited Strings
With general delimited strings, you can create strings inside a pair of matching though arbitrary delimiter characters, e.g., !, (, {, <, etc., preceded by a percent character (%). Q, q, and x have special meanings. General delimited strings can be −%{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
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'
String Built-in Methods
We need to have an instance of String object to call a String method. Following is the way to create an instance of String object −new [String.new(str = "")] This will return a new string object containing a copy of str. Now, using str object, we can all use any available instance methods. For example −
Live Demo #!/usr/bin/ruby myStr = String.new("THIS IS TEST") foo = myStr.downcase puts "#{foo}" This will produce the following result −
this is test
String unpack Directives
Example
Try the following example to unpack various data."abc \0\0abc \0\0".unpack('A6Z6') #=> ["abc", "abc "] "abc \0\0".unpack('a3a3') #=> ["abc", " \000\000"] "abc \0abc \0".unpack('Z*Z*') #=> ["abc ", "abc "] "aa".unpack('b8B8') #=> ["10000110", "01100001"] "aaa".unpack('h2H2c') #=> ["16", "61", 97] "\xfe\xff\xfe\xff".unpack('sS') #=> [-2, 65534] "now = 20is".unpack('M*') #=> ["now is"] "whole".unpack('xax2aX2aX1aX2a') #=> ["h", "e", "l", "l", "o"]
No comments:
Post a Comment