SL Notes
SL Notes
Introduction: Ruby, Rails, The structure and Execution of Ruby Programs, Package Management with
RUBYGEMS, Ruby and web: Writing CGI scripts, cookies, Choice of Webservers, SOAP and webservices.
RubyTk – Simple Tk Application, widgets, Binding events, Canvas, scrolling
UNIT - II
Extending Ruby: Ruby Objects in C, the Jukebox extension, Memory allocation, Ruby Type System, Embedding
Ruby to Other Languages, Embedding a Ruby Interperter
UNIT - III
Introduction to PERL and Scripting
Scripts and Programs, Origin of Scripting, Scripting Today, Characteristics of Scripting Languages,Uses for
Scripting Languages, Web Scripting, and the universe of Scripting Languages. PERL- Names and Values,
Variables, Scalar Expressions, Control Structures, arrays, list, hashes, strings, pattern and regular expressions,
subroutines.
UNIT - IV
Advanced PERL
Finer points of looping, pack and unpack, filesystem, eval, data structures, packages, modules, objects,
interfacing to the operating system, Creating Internet ware applications, Dirty Hands Internet Programming,
security Issues.
UNIT - V
TCL: TCL Structure, syntax, Variables and Data in TCL, Control Flow, Data Structures, input/output,
procedures, strings, patterns, files, Advance TCL- eval, source, exec and uplevel commands, Name spaces,
trapping errors, event driven programs, making applications internet aware, Nuts and Bolts Internet
Programming, Security Issues, C Interface.
Tk: Tk-Visual Tool Kits, Fundamental Concepts of Tk, Tk by example, Events and Binding, Perl-Tk.
Introduction to Scripting Languages
• All scripting languages are programming languages.
• Progarmming Languages:c,c++,java
• The scripting language is basically a language where
instructions are written for a run time environment.
They do not require the compilation step and are
rather interpreted.
• A scripting language is a programming language
designed for integrating and communicating with
other programming languages.
Advantages of scripting languages:
• Easy learning: The user can learn to code in scripting languages
quickly, not much knowledge of web technology is required.
• Fast editing: It is highly efficient with the limited number of
data structures and variables to use.
• Interactivity: It helps in adding visualization interfaces and
combinations in web pages. Modern web pages demand the
use of scripting languages. To create enhanced web pages,
fascinated visual description which includes background and
foreground colors and so on.
• Functionality: There are different libraries which are part of
different scripting languages. They help in creating new
applications in web browsers and are different from normal
programming languages.
Application of Scripting Languages: Scripting languages are
used in many areas:
• Scripting languages are used in web applications. It is
used in server side as well as client side.
• Server side scripting languages are: JavaScript, PHP, Perl
etc.
• client side scripting languages are: JavaScript, AJAX,
jQuery etc.
• Scripting languages are used in system administration.
For example: Shell, Perl, Python scripts etc.
• It is used in Games application and Multimedia.
• It is used to create plugins and extensions for existing
applications.
Compiler vs Interpreter
• A compiler takes entire program and converts it into
object code which is typically stored in a file. The object
code is also referred as binary code and can be directly
executed by the machine after linking. Examples of
compiled programming languages are C and C++.
• An Interpreter directly executes instructions written in
a programming or scripting language without
previously converting them to an object code or
machine code. Examples of interpreted languages are
Perl, Python and Matlab.
Following are some interesting facts about interpreters and
compilers.
• 1) Both compilers and interpreters convert source code (text files)
into tokens, both may generate a parse tree, and both may
generate immediate instructions. The basic difference is that a
compiler system, including a (built in or separate) linker, generates
a stand alone machine code program, while an interpreter system
instead performs the actions described by the high level program.
• 2) Once a program is compiled, its source code is not useful for
running the code. For interpreted programs, the source code is
needed to run the program every time.
• 3) In general, interpreted programs run slower than the compiled
programs.
• 4) Java programs are first compiled to an intermediate form, then
interpreted by the interpreter.
• Server-side Scripting
• It helps work with the back end.
• It doesn’t depend on the client.
• It runs on the web server.
• It helps provide a response to every request that comes in from
the user/client.
• This is not visible to the client side of the application.
• It requires the interaction with the server for the data to be
process.
• Server side scripting requires languages such as PHP, ASP.net,
ColdFusion, Python, Ruby on Rails.
• It is considered to be a secure way of working with applications.
• It can be used to customize web pages.
• It can also be used to provide dynamic websites.
• Client-side Scripting
• It helps work with the front end.
• It is visible to the users.
• The scripts are run on the client browser.
• It runs on the user/client’s computer.
• It depends on the browser’s version.
• It doesn’t interact with the server to process data.
• Client side scripting involves languages such as HTML,
CSS, JavaScript.
• It helps reduce the load on the server.
• It is considered to be less secure in comparison to
client side scripting.
Ruby is a pure object-oriented programming
language. It was created in 1993 Japan by
Yukihiro Matsumoto, also known as Matz.
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 object-oriented
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 Webe
• 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 embedded into Hypertext Markup Language (HTML).
• Ruby has a clean and easy syntax that allows a new developer to learn 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 Linux environments.
• Ruby support many GUI tools such as Tcl.
• 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.
• Ruby is being used in wide range of fields, especially in Web
Applications and data science.
• Ruby is a dynamic programming language therefore, it does not have
hard rules on how to build features and it is very close to spoken
languages.
• One of the goals of Ruby is to allow the simple and fast creation of Web
applications. Because of this there is much less tedious work than many
other programming languages.
• Ruby provides small, elegant and powerful code.
• Ruby is an open source language. It is free to copy, use, modify and
distribute. Since Ruby is available to be used in other projects,
programmers can make necessary changes and can code without
feeling restricted.
• Programmers are allowed to maintain reference counts in extension
libraries with the help of mark-and-sweep garbage collection, which is
one of the features of Ruby. It can also dynamically load extension
libraries.
Difference between Ruby and Ruby on Rails :
• Ruby is a programming language whereas
Ruby on Rails is a Web framework.
• Ruby is an Object Oriented, dynamic,
interpreted scripting language whereas Ruby
on Rails is an Open source Web application
framework, which runs on the Ruby
programming language.
• Ruby on Rails :
Ruby on Rails (RoR) is an open source Web
application frameworks. Ruby on Rails is one
of the main features of Ruby. The
programming language, Ruby is used to write
Ruby on Rails. Ruby on Rails, simply called
Rails was designed for Ruby by David
Heinemeier Hansson. It was released in July
2004.
Ruby versus Java :
• Ruby based program runs directly as it is an
interpreted scripting language whereas Java-
based codes are first compiled then executed.
• Ruby does not have any data types as Java.
• In Ruby the constructor name is always
“initialize” whereas in case of Java the
constructor name is the name of the class.
• Ruby uses dynamic typing whereas Java uses
static typing.
static typing vs dynamic typing
dynamically-typed languages perform type
checking at runtime, while statically typed
languages perform type checking at compile
time. ... If a script written in a statically-typed
language (such as Java) contains errors, it will
fail to compile until the errors have been fixed.
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
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.
• 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.rb
• This will produce the following result −
• Hello, Ruby!
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.
• A
• a
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.
When
BEGIN And Case
Do End For
Next Or Retry
Then Unless While
END Begin Class
Else Ensure If
Nil reDo Return
True Until While
Alias Break Definse
Elsif False lf__FILE__
Not Rescue Defined
Undef ?
Module
Super
__LINE__
Ruby Is Object-Oriented
• Ruby is a completely object-oriented language. Every value is an object, even
simple numeric literals and the values true, false, and nil (nil is a special value
that indicates the absence of value; it is Ruby’s version of null). Here wevoke a
method named class on these values. Comments begin with # in Ruby, and the
=> arrows in the comments indicate the value returned by the commented code
•
• 1.class # => Fixnum: the number 1 is a Fix num
•
• 0.0.class # => Float: floating-point numbers have class Float
•
• true.class # => TrueClass: true is a the singleton instance of TrueClass
•
• false.class # => FalseClass
•
• nil.class # => NilClass
•
Blocks and Iterators
• They are a special kind of method known as an
iterator, and they behave like loops.
• The code within curly braces —known as a
block—is associated with the method
invocation and serves as the body of the loop.
• The use of iterators and blocks is another
notable feature of Ruby; although the
language does support an ordinary while loop,
it is more common to perform loops with
constructs that are actually method calls.
• 3.times { print "Ruby! " } # Prints "Ruby! Ruby!
Ruby! "
•
• 1.upto(9) {|x| print x } # Prints "123456789"
• 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 comment
• You can comment multiple lines as follows −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
• Ruby vs Perl – Differences
• Following are some of the basic differences of Ruby vs Perl:
• 2. Web Frameworks
• In the matter of Ruby vs Perl, Catalyst is a major and most used Perl-based web
framework while Ruby on rails is a major web framework used for Ruby. Ruby on
Rails is an open-source web application framework. To write in this, Ruby
programming language is used.
• 3. Unicode Support
• When it comes to Unicode support, Perl language has much stronger support for
Unicode than Ruby language. For example, Perl supports all Unicode properties,
graphemes, and full case mapping.
• Ruby programming language do not support all these.
• 4. Object Orientation
• Ruby language is a pure object-oriented programing language.
But Pearl, up to the 5th version, is very less objective-oriented.
But the upcoming version of Pearl is coming with very good OO
support.
end
E.g: class Customer
end
• Creating Objects using the “new” method in
Ruby:
Classes and objects are the most important
part of Ruby. Like class objects are also easy to
create, we can create a number of objects
from a single class. In Ruby, objects are
created by the new method.
Syntax:
• object_name = Class_name.new
• Defining Method in Ruby:
In Ruby member functions are called as
methods.
• Every method is defined by the def
keyword followed by a method name. The
name of the method is always in lowercase
and the method ends with end keyword. In
Ruby, each class and methods end with end
keyword.
# Ruby program to illustrate
# defining class Vehicle
class GFG
# defining method
def geeks
# printing result
puts "Hello Geeks!"
# end of method
end
# creating object
obj = GFG.new
• Hello Geeks!
x=classname.new
x.geeks
• Ruby | Constructors
• A constructor is a special method of the class which gets automatically
invoked whenever an instance of the class is created. Like methods, a
constructor may also contain the group of instructions or a method which
will execute at the time of object creation.
• Important points to remember about Constructors:
• Constructors are used to initialize the instance variables.
• In Ruby, the constructor has a different name, unlike other programming
languages.
• A constructor is defined using the initialize and def keyword.
• It is treated as a special method in Ruby.
• Constructor can be overloaded in Ruby.
• Constructors can’t be inherited.
• It returns the instance of that class.
• Note: Whenever an object of the class is created using new method,
internally it calls the initialize method on the new object. Also, all the
arguments passed to new will automatically pass to method initialize.
• Syntax:
class Class_Name
def initialize(parameter_list)
end
end
# class name
class Demo
# constructor
def initialize
puts "Welcome to GeeksforGeeks!"
end
end
# Creating Obejct
x= Demo.new
• Output:
• Welcome to GeeksforGeeks!
Ruby BEGIN Statement
Syntax
BEGIN {
code
code2
}
• Declares code to be called before the program is run.
Example
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
}
#!/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
Ruby | Types of Variables
• There are different types of variables in Ruby:
• Local variables
• Instance variables
• Class variables
• Global variables
• Each variable in Ruby is declared by using a
special character at the start of the variable
name which is mentioned in the following table:
• Symbol Type of Variable
• [a-z] or _ Local Variable
• @ Instance Variable
• @@ Class Variable
• $ Global Variable
• Local Variables: A local variable name always
starts with a lowercase letter(a-z) or
underscore (_). These variables are local to the
code construct in which they are declared. A
local variable is only accessible within the block
of its initialization. Local variables are not
available outside the method. There is no need
to initialize the local variables.
• Example:
• age = 10
• _Age = 20
• Instance Variables: An instance variable name
always starts with a @ sign. They are similar to
Class variables but their values are local to
specific instances of an object. Instance
variables are available across methods for any
specified instance or object i.e. instance
variables can change from object to object.
There is no need to initialize the instance
variables and uninitialized instance variable
always contains a nil value.
class Customer
# Instance Variables
@cust_id = id
@cust_name = name
@cust_addr = addr
end
# displaying result
Output:
def display_details()
puts "Customer id #@cust_id" Customer id 1 Customer name John Customer
puts "Customer name #@cust_name" address Wisdom Apartments, Ludhiya
puts "Customer address #@cust_addr" Customer id 2 Customer name Poul Customer
end address New Empire road, Khandala
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()
• Class Variables: A class variable name always
starts with @@ sign.It is available across
different objects. A class variable belongs to
the class and it is a characteristic of a class.
They need to be initialized before use.
Another way of thinking about class variables
is as global variables within the context of a
single class. A class variable is shared by all the
descendants of the class. An uninitialized class
variable will result in an error.
• class Customer
•
• # class variable
• @@no_of_customers = 0
•
• def initialize(id, name, addr)
•
• # An instance Variable
• @cust_id = id
• @cust_name = name
• @cust_addr = addr
• end
•
• # displaying result
• def display_details()
• puts "Customer id #@cust_id"
• puts "Customer name #@cust_name"
• puts "Customer address #@cust_addr"
• end
•
• def total_no_of_customers()
•
• # class variable
• @@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.display_details()
• cust1.total_no_of_customers()
• cust2.display_details()
• cust2.total_no_of_customers()
• Output:
• Customer id 1
• Customer name John
• Customer address Wisdom Apartments, Ludhiya
• Total number of customers: 1
• Customer id 2
• Customer name Poul
• Customer address New Empire road, Khandala
• Total number of customers: 2
2.The Structure and Execution of
Ruby Programs
This chapter explains the structure of Ruby
programs.
•lexical structure,covering tokens and the characters
that comprise them.
•Syntactic structure, explaining how expressions,
control structures, methods,classes, and so on are
written as a series of tokens.
•files, explaining how Ruby programs can be split
across multiple files and how the Ruby interpreter
executes a file of Ruby code
Ruby lexical structure
• Computer languages, like human languages,
have a lexical structure.
• A source code of a Ruby program consists of
tokens. Tokens are atomic code elements.
• In Ruby language we have various lexical
structures, such as comments, variables,
literals, white space, operators, delimiters,
and keywords.
• Lexical Structure
• The Ruby interpreter parses a program as a sequence of
tokens.
• Tokens include
• comments,
• literals
• punctuation,
• identifiers, and
• keywords.
This section introduces these types of tokens and also
includes important information about the characters that
comprise the tokens and the whitespace that separates the
tokens.
Comments
• Comments are used by humans to clarify the source code.
There are two types of comments in Ruby. Single-line and
multi-line comments. Single-line comments begin with
the #character. Multi-line comments are put between
the =begin and =end tokens.
• Comments in Ruby begin with a # character and continue to the
end of the line.
• The Ruby interpreter ignores the # character and any text that
follows it (but does not ignore the newline character, which is
meaningful whitespace and may serve as a statement
terminator).
• # This entire line is a comment
• Multiline comments are usually written simply
by beginning each line with a separate
# character:
#
# This class represents a Complex number
# Despite its name, it is not complex at all.
#
Note that Ruby has no equivalent of the C-
style /*...*/ comment.
• =begin
comments.rb
author Jan Bodnar
=end
# prints message to the terminal puts
"Comments example"
Embedded documents
• Ruby supports another style of multiline
comment known as an embedded document.
These start on a line that begins =begin and
continue until (and include) a line that
begins =end.
Any text that appears after =begin or =end is
part of the comment and is also ignored, but
that extra text must be separated from the
=begin and =end by at least one space.
=begin Someone needs to fix the broken code
below!
Any code here is commented out
=end
• Ruby white space
• White space in Ruby is used to separate tokens and terminate
statements in the source file. It is also used to improve readability of the
source code.
if true then
puts "A message"
end
White spaces are required in some places. For example between
the if keyword and the true keyword. Or between the puts method and
the actual string. In other places, it is forbidden. It cannot be present in
variable identifiers or language keywords.
• a=1
• b=2
• c=3
• The amount of space put between tokens is irrelevant for the Ruby
interpreter. However, it is important to have one style throughout the
project.
x=5+3
puts x
y=5
+3
puts y
z=5+
3
Puts z
O/P:
8
5
8
Literals
Literals are values that appear directly in Ruby source code.
They include numbers,strings of text, and regular
expressions.
A literal is a textual representation of a particular value of a
type. Literal types include boolean, integer, floating point,
string, character, and date. Technically, a literal will be
assigned a value at compile time, while a variable will be
assigned at runtime.
1 # An integer literal
1.0 # A floating-point literal
'one‘ # A string literal
"two" # Another string literal
/three/ # A regular expression literal
Punctuation
• Ruby uses punctuation characters for a number
of purposes.
• Most Ruby operators are written using
punctuation characters, such as + for addition,
* for multiplication, and || for the Boolean
OR operation.
• 2.4 Identifiers
• An identifier is simply a name. Ruby uses identifiers to
name variables, methods, classes,and so forth.
• Ruby identifiers consist of letters, numbers, and
underscore characters,but they may not begin with a
number.
• Identifiers may not include whitespace and they may not
include punctuation characters except as described here
• A variable is an identifier, which holds a value. In
programming we say that we assign a value to a variable.
Technically speaking, a variable is a reference to a
computer memory, where the value is stored. In Ruby, a
variable can hold a string, a number or various objects.
Variables can be assigned different values over time.
• Identifiers that begin with a capital letter A–Z are constants,
and the Ruby interpreter will issue a warning (but not an error)
if you alter the value of such an identifier.
• Class and module names must begin with initial capital letters.
• The following are identifiers:
i
x2
old_value
• _internal # Identifiers may begin with underscores
• PI # Constant
• By convention, multiword identifiers that are not constants are
written with underscores
• like_this, whereas multiword constants are written LikeThis or
LIKE_THIS
• Value
• value2
• company_name
These are valid variable names.
• 12Val
• exx$
• first-name
These are examples of invalid variable names.
• 2.4.1 Case sensitivity
• Ruby is a case-sensitive language. Lowercase
letters and uppercase letters are distinct.
• The keyword end, for example, is completely
different from the keyword END.
• Sample=10
• Puts “SAMPLE”
Punctuation in identifiers
• Punctuation characters may appear at the start and end of
Ruby identifiers
• Here are some example identifiers that contain leading or
trailing punctuation
• characters:
• $files # A global variable
• @data # An instance variable
• @@counter # A class variable
• empty? # A Boolean-valued method or predicate
• sort! # An in-place alternative to the regular sort
method
• Timeout = # A method invoked by assignment
• A number of Ruby’s operators are implemented as methods, so
that classes can redefine them for their own purposes
• 2.4.3 Keywords
• The following keywords have special meaning
in Ruby and are treated specially by the Ruby
parser:
• Ruby delimiters
• A delimiter is a sequence of one or more
characters used to specify the boundary
between separate, independent regions in
plain text or other data stream
• ()[]{},;'"||
• name = "Jane"
• occupation = 'Student'
• numbers = [ 2, 3, 5, 3, 6, 2 ]
• puts name;
• puts occupation
• puts numbers[2]
• numbers.each { |i| puts i } puts ( 2 + 3 ) * 5
name = "Jane"
occupation = 'Student'
• Single and double quotes are used to delimit a string in
Ruby.
numbers = [ 2, 3, 5, 3, 6, 2 ]
• The square brackets are used to set boundaries for an
array. The commas are used to separate items in the array.
puts name; puts occupation
• The semicolon is used in Ruby to separate two statements
in a Ruby source code.
puts numbers[2]
• Delimiters can be used in different contexts. Here the
square brackets are used to access an item in the array.
• Ruby operators
• An operator is a symbol used to perform an action on some value.
(answers.com)
• !
• +
• -
• ~
• *
• **
• /
• %
• << >>
• & | ^ == === != <=> >= > < <= = %= /= -=
+= *= **= .. ... not and or ?:
• && ||
• Ruby blocks
• Ruby statements are often organized into
blocks of code. A code block can be delimited
using { } characters or do and end keywords.
• Flow control of Ruby code is often done with
the if keyword. The keyword is followed by a block
of code. In this case a block of code is delimited
by then, end keywords, where the first keyword is
optional.
if true then
puts "Ruby language"
puts "Ruby script"
end
In the above example, we have a simple block of code. It
has two statements. The block is delimited
by then, end keywords. The then keyword can be
omitted
• Ruby constants
• Constants are value holders which hold only
one value over time. An identifier with a first
uppercase letter is a constant in Ruby. In
programming it is a convention to write all
characters of a constant in uppercase.
• Unlike in other languages, Ruby does not
enforce constants to have only one value over
time. The interpreter only issues a warning if
we assign a new value to an existing constant.
• Name = "Robert"
• AGE = 23
• Name = "Juliet“
• In the above example, we create two
constants. One of the constants is redefined
later.
• We redefine a constant. Which issues a
warning.
Syntactic Structure
• Now we move on to briefly describe how
those lexical tokens combine into the larger
syntactic structures of a Ruby program
• This section describes the syntax of Ruby
programs, from the simplest expressions to
the largest modules
• Operators are used to perform computations
on values, and compound expressions are
built by combining simpler subexpressions
with operators:
• 1 # A primary expression
• x # Another primary expression
• x = 1 # An assignment expression
• x = x + 1 # An expression with two operators
• Expressions can be combined with Ruby’s
keywords to create statements, such as the
• if statement for conditionally executing code
and the while statement for repeatedly
executing code:
if x < 10 then # If this expression is true
x = x + 1 # Then execute this statement
end # Marks the end of the conditional
• while x < 10 do # While this expression is
true...
• print x # Execute this statement
• x = x + 1 # Then execute this statement
• end # Marks the end of the loop
Block Structure in Ruby
• Module, class, and method definitions, and most of
Ruby’s statements, include blocks of nested code.
• These blocks are delimited by keywords or
punctuation and, by convention, are indented two
spaces relative to the delimiters.
• There are two kinds of blocks in Ruby programs.
One kind is formally called a “block.” These blocks
are the chunks of code associated with or passed to
iterator methods:
• 3.times { print "Ruby! " }
File Structure
• First, if a Ruby program contains a “shebang” comment, to tell
the (Unix-like) operating system how to execute it, that comment
must appear on the first line.
• Second, if a Ruby program contains a “coding” comment (as
described in §2.4.1), that comment must appear on the first line
or on the second line if the first line is a shebang.
• Third, if a file contains a line that consists of the single token
__END__ with no whitespace before or after, then the Ruby
interpreter stops processing the file at that point.
• The remainder of the file may contain arbitrary data that the
program can read using the
• IO stream object DATA
• #!/usr/bin/ruby -w shebang comment
• # -*- coding: utf-8 -*- coding comment
• require 'socket' load networking library
• ... program code goes here
• __END__ mark end of code
• ... program data goes here
Program Execution
• Ruby is a scripting language. This means that
Ruby programs are simply lists, or scripts, of
statements to be executed. By default, these
statements are executed sequentially, in the
order they appear. Ruby’s control structures
alter this default execution order and allow
statements to be executed conditionally or
repeatedly
• Programmers who are used to traditional
static compiled languages like C or Java may
find this slightly confusing.
• There is no special main method in Ruby
from which execution begins.
• The Ruby interpreter is given a script of
statements to execute, and it begins
executing at the first line and continues to
the last line.
• Actually, that last statement is not quite true.
The Ruby interpreter first scans the file for
BEGIN statements, and executes the code in
their bodies. Then it goes back to line 1 and
starts executing sequentially.
Ruby if...else Statement
if conditional [then]
code...
[elsif conditional [then]
code...]...
[else code...]
end
x=1
if x > 2
puts "x is greater than 2"
elsif x <= 2 and x!=0
puts "x is 1"
else
puts "I can't guess the number"
end
Ruby while Statement
• 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.
while conditional [do]
code
end
$i = 0
$num = 5
while $i <$num do
puts("Inside the loop i = #$i" )
$i +=1
End
• This will produce the following result −
Inside the loop i=0
Inside the loop i=1
Inside the loop i=2
Inside the loop i=3
Inside the loop i=4
• Ruby for Statement
• Syntax
for variable [, variable ...] in expression [do]
code
end
for i in 0..5
puts "Value of local variable is #{i}"
End
Output
Value of local variable is 0
Value of local variable is 1
Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
For (i=0;i<=5;i++)
• Ruby Gems
• RubyGems is a package utility for Ruby, which
installs Ruby software packages and keeps
them up-to-date.
• Check to see whether RubyGems is installed −
• $ gem --version
• 0.9.0
• How do RubyGems work?
• The RubyGems software allows you to easily
download, install, and use ruby software
packages on your system. ... Gems can be
used to extend or modify functionality in
Ruby applications. Commonly they're used to
distribute reusable functionality that is shared
with other Rubyists for use in their
applications and libraries.
Ruby Package Management with gem
• Ruby’s package management system is known
as RubyGems, and packages or modules
distributed using RubyGems are called “gems.”
• RubyGems makes it easy to install Ruby
software and can automatically manage
complex dependencies between packages.
• RubyGems is a standardized packaging and installation
framework for libraries and applications, making it
easy to locate, install, upgrade, and uninstall Ruby
packages
• It provides users and developers with four main
facilities.
• 1. A standardized package format,
• 2. A central repository for hosting packages in this
format,
• 3. Installation and management of multiple,
simultaneously installed versions of the same library,
• 4. End-user tools for querying, installing, uninstalling,
and otherwise manipulating these packages.
• Before RubyGems came along, installing a new
library involved searching the Web,
downloading a package, and attempting to
install it—only to find that its dependencies
haven’t been met.
• If the library you want is packaged using
RubyGems, however, you can now simply ask
RubyGems to install it (and all its
dependencies). Everything is done for you.
• In the RubyGems world, developers bundle
their applications and libraries into single files
called gems.
• These files conform to a standardized format,
and the RubyGems system provides a
command-line tool, appropriately named gem,
for manipulating these gem files.
The gem command allows you to interact with
RubyGems.
FINDING GEMS
The search command lets you find remote gems
by name. You can use regular expression
characters in your query:
• If you see a gem you want more information
on you can add the details option.
• INSTALLING GEMS
• The install command downloads and installs
the gem and any necessary dependencies
then builds documentation for the installed
gems.
• LISTING INSTALLED GEMS
• The list command shows your locally installed
gems:gem has other useful subcommands as
well. Some examples:
• gem list # List installed gems
• gem enviroment # Display RubyGems
configuration information
• gem update rails # Update a named gem
• gem update # Update all installed gems
• gem update –system # Update RubyGems itself
• gem uninstall rails # Remove an installed gem
• UNINSTALLING GEMS
• The uninstall command removes the gems you
have installed.
STRUCTURE OF A GEM
The above code is producing an HTML form having title "This is an example". The
form has horizontal rulers, Headings, two Input controls namely TextArea and
button. All the code blocks will return a string which will be utilized as the content
for the tag.
Cookies
• Cookies are a way of letting Web applications store their
state on the user’s machine.
• cookies are still a convenient (if unreliable) way of
remembering session information.
• The Ruby CGI class handles the loading and saving of
cookies for you. You can access the cookies associated
with the current request using the CGI#cookies method,
and you
• can set cookies back into the browser by setting the
cookies parameter of CGI#out to
• reference either a single cookie or an array of cookies.
#!/usr/bin/ruby
COOKIE_NAME = 'chocolate chip'
require 'cgi'
cgi = CGI.new
values = cgi.cookies[COOKIE_NAME]
if values.empty?
msg = "It looks as if you haven't visited recently"
else
msg = "You last visited #{values[0]}"
end
cookie = CGI::Cookie.new(COOKIE_NAME, Time.now.to_s)
cookie.expires = Time.now + 30*24*3600 # 30 days
cgi.out("cookie" => cookie ) { msg }
• Ruby/Tk Introduction
• The standard graphical user interface (GUI) for Ruby
is Tk. Tk started out as the GUI for the Tcl scripting
language developed by John Ousterhout.
• Tk has the unique distinction of being the only
cross-platform GUI. Tk runs on Windows, Mac, and
Linux and provides a native look-and-feel on each
operating system.
• The basic component of a Tk-based application is
called a widget. A component is also sometimes
called a window, since, in Tk, "window" and
"widget" are often used interchangeably.
• Tk applications follow a widget hierarchy where any
number of widgets may be placed within another widget,
and those widgets within another widget, ad infinitum.
• The main widget in a Tk program is referred to as the root
widget and can be created by making a new instance of
the TkRoot class.
• The traditional Hello, World! example for Ruby/Tk looks something like
this −
require 'tk’
x
root = TkRoot.new { title "Hello, World!" }
TkLabel.new(root) do
text 'Hello, World!'
pack { padx 15 ; pady 15; side 'left' }
end
Tk.mainloop
• Ruby/Tk Widget Classes
• There is a list of various Ruby/Tk classes, which can be used to create a desired GUI using
Ruby/Tk.
• There are three geometry managers place, grid and pack that
are responsible for controlling the size and location of each of
the widgets in the interface.
• Syntax
• Here is a simple syntax to create a grid Widget −
• grid('row'=>x, 'column'=>y)
• Examples
• Following is the code to display the Label and an Entry widget using
the grid geometry manager −
• require 'tk'
• Tk.mainloop
• Ruby/TK - The pack geometry manager
• The pack geometry manager organizes widgets in rows or columns inside the
parent window or the widget. To manage widgets easily, the pack geometry
manager provides various options, such as fill, expand, and side.
• fill − The fill option is used to specify whether a widget should occupy all the
space given to it by the parent window or the widget. Some of the possible
values that can be used with this option are none, x, y, or both. By default,
the fill option is set to none.
• side − The side option is used to specify the side against which the widget is
to be packed. Some of the possible values that can be used with this option
are top, left, bottom, or right. By default, the widgets are packed against the
top edge of the parent window.
• Syntax
• Here is a simple syntax to create a pack
Widget −
• Tk.mainloop
• Ruby/TK - The place geometry manager
• The place geometry manager allows you to place a
widget at the specified position in the window. You
can specify the position either in absolute terms or
relative to the parent window or the widget.
• place(relx'=>x, 'rely'=>y)
• Examples
• Following is the code which implements the place geometry manager −
• require 'tk'
• Tk.mainloop
• Ruby/TK - Canvas Widget
• A Canvas widget implements structured
graphics. A canvas displays any number of
items, which may be things like rectangles,
circles, lines, and text.
• Syntax
TkCanvas.new {
.....Standard Options....
.....Widget-specific Options....
}
Creating Items
• When you create a new canvas widget, it will
essentially be a large rectangle with nothing on it;
truly a blank canvas in other words. To do anything
useful with it, you'll need to add items to it.
• there are a wide variety of different types of items
you can add
• Arc Items
• Bitmap Items
• Image Items
• Line Items
• Rectangle Items
• Arc Items
• Items of type arc appear on the display as arc-shaped
regions. An arc is a section of an oval delimited by
two angles. Arcs are created with methods of the
following form −
• fill => color − Fills the region of the arc with color.
• outline => color − Color specifies a color to use for drawing the arc's outline.
• start => degrees − Specifies the beginning of the angular range occupied by the arc.
• style => type − Specifies how to draw the arc. If type is pieslice (the default) then the arc's
region is defined by a section of the oval's perimeter plus two line segments, one between
the center of the oval and each end of the perimeter section. If type is chord then the arc's
region is defined by a section of the oval's perimeter plus a single line segment connecting
the two end points of the perimeter section. If type is arc then the arc's region consists of a
section of the perimeter alone.
• tags => tagList − Specifies a set of tags to apply to the item. TagList consists of a list of tag
names, which replace any existing tags for the item. TagList may be an empty list.
• width => outlineWidth − Specifies the width of the outline to be drawn around the arc's
region.
• Image Items
• Items of type image are used to display images on
a canvas. Images are created with methods of the
following form: :
• tags => tagList − Specifies a set of tags to apply to the item. TagList
consists of a list of tag names, which replace any existing tags for
the item. TagList may be an empty list.
• Line Items
• Items of type line appear on the display as one or
more connected line segments or curves. Lines
are created with methods of the following form −
• fill => color − Fills the area of the rectangle with color.
• outline => color − Draws an outline around the edge of the rectangle
in color.
• tags => tagList − Specifies a set of tags to apply to the item. TagList
consists of a list of tag names, which replace any existing tags for the
item. TagList may be an empty list.
• canvas = TkCanvas.new
• TkcRectangle.new(canvas, '1c', '2c', '3c', '3c',
'outline' => 'black', 'fill' => 'blue')
• TkcLine.new(canvas, 0, 0, 100, 100, 'width' =>
'2', 'fill' => 'red')
• canvas.pack
• Tk.mainloop
• Ruby/Tk – Scrollbar Widget
• A Scrollbar helps the user to see all parts of
another widget, whose content is typically
much larger than what can be shown in the
available screen space.
TkScrollbar.new {
.....Standard Options....
.....Widget-specific Options....
}
• require "tk"
• canvas = TkCanvas.new
• TkcRectangle.new(canvas, '1c', '2c', '3c', '3c',
'outline' => 'black', 'fill' => 'blue')
• TkcLine.new(canvas, 0, 0, 100, 100, 'width' =>
'2', 'fill' => 'red')
• canvas.pack
• Tk.mainloop
• Elements of Scrollbar
• A scrollbar displays five elements, which are referred in the
methods for the scrollbar −