SlideShare a Scribd company logo
1 of 166
SCRIPTING LANGUAGES (Open Elective - III)
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.
And
End
Or
Unless
Begin
Ensure
reDo
Until
Break
False
Rescue
When
Case
For
Retry
While
Class
If
Return
While
Definse
lf__FILE__
Defined
?
Module
Super
__LINE__
BEGIN
Do
Next
Then
END
Else
Nil
True
Alias
Elsif
Not
Undef
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:
• 1. Development and Release
• Perl programming language was developed by Larry Wall and released in
the year of 1987. Ruby is a newcomer in the programming industry. And it
was developed and released in 1995 by Yukihiro Matsumoto.
• 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.
• Objective-oriented programming stands for a physical
model of programming execution. It simulates the behavior
of either a real or imaginary part of the world.
• The developer of Perl believes that choosing of OO should
be the programmer’s decision; language should not force a
programmer to switch to OO.
• Ruby also doesn’t force you to choose an objective
orientation, but if you do, it will be much easier to use than
in Perl.
5. Supporting of Regular Expression
• When we start a discussion on supporting of a
regular expression, Perl has a very good
number of libraries than Ruby has. The Perl
library of code CPAN is incomparable with any
other library.
• So the supporting capacity of regular
expression of Perl is little more than Ruby. But
you need not worry as a user of Ruby, as it
supports most of the regular expressions.
• 8. Variable Type
• Perl has multiple variable types like a scalar,
array, hash, etc. in contrast, Ruby
programming language offers only one
variable type: reference to the object, the
object can act like an array, hash, or whatever,
depends on demand.
• 9. Use of Sigils
• Perl uses the sigils like @, $, and % to denote
variable types. Ruby uses sigils such as @,
@@, and $ to denote scope. To use all the
variables in Perl except function, the user has
to put some sigils.
• But in the case of Ruby, there is no need for
variables to work with local scopes.
• 10. File Extension
• A file extension is another major difference
between Perl and Ruby. Perl programs have
the .pl file extension while Ruby programs
have the .rb file extension.
• 11. Influenced Language
• Perl is influenced by C, Basic, Lisp, Ada, etc. It
mainly resembles with C language. On the
other hand, Ruby is influenced by C, Perl,
Smalltalk, Ada, Lisp, etc. Ruby has some
additional touch from Smalltalk which is
missing in Perl.
• Conclusion
• Perl is a quite old language, started its journey
eight years ago than Ruby does. So, in the cases
of community backup, availability of libraries for
any need, documentation, Perl is far ahead of
Ruby. Ruby has its merits in providing object-
oriented features that help in keeping large code
bodies maintainable.
• So, both have some sort of merits and demerits.
So, in the competition of Ruby vs Perl, the choice
of language depends completely on the
programmer.
Ruby | Class & Object
• In object-oriented programming classes and
objects plays an important role.
A class is a blueprint from which objects are
created. The object is also called as an instance of
a class.
For Example, the animal is a class and mammals,
birds, fish, reptiles, and amphibians are the
instances of the class. Similarly, the sales
department is the class and the objects of the
class are sales data, sales manager, and secretary.
Defining a class in Ruby:
• In Ruby, one can easily create classes and objects. Simply
write class keyword followed by the name of the class. The
first letter of the class name should be in capital letter.
Syntax:
class Class_name
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
# end of class GFG
end
# creating object
obj = GFG.new
# calling method using object
obj.geeks
• Output:
• 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
def initialize(id, name, addr)
# Instance Variables
@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
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()
Output:
Customer id 1 Customer name John Customer
address Wisdom Apartments, Ludhiya
Customer id 2 Customer name Poul Customer
address New Empire road, Khandala
• 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
• each gem has a name, version, and platform.
For example, the rake gem has a 0.8.7 version
(from May, 2009). Rake’s platform is ruby,
which means it works on any platform Ruby
runs on.
• Platforms are based on the CPU architecture,
operating system type and sometimes the
operating system version. Examples include
“x86-mingw32” or “java”. The platform
indicates the gem only works with a ruby built
for the same platform.
• RubyGems will automatically download the
correct version for your platform. See gem
help platform for full details.
• Inside gems are the following components:
• Code (including tests and supporting utilities)
• Documentation
• gemspec
• THE GEMSPEC
• The gemspec specifies the information about
a gem such as its name, version, description,
authors and homepage.
The lib directory contains the code for the gem
The test or spec directory contains tests, depending on which test framework
the developer uses
A gem usually has a Rakefile, which the rake program uses to automate tests,
generate code, and perform other tasks.
This gem also includes an executable file in the bin directory, which will be
loaded into the user’s PATH when the gem is installed.
Documentation is usually included in the README and inline with the code.
When you install a gem, documentation is generated automatically for you.
Most gems include RDoc documentation
• In this chapter, we’ll see how to
• 1. Install RubyGems on your computer.
• 2. Use RubyGems to install other applications
and libraries.
• 3. Write your own gems.
Installing RubyGems
• To use RubyGems, you’ll first need to
download and install the RubyGems system
from the project’s home page at
http://rubygems.rubyforge.org
• % cd rubygems0.7.0
• % ruby install.rb
• The best way to test that RubyGems was
installed successfully also happens to be the
• most important command you’ll learn.
• % gem help
Installing Application Gems
• Let’s start by using RubyGems to install an
application that is written in Ruby. Jim
Weirich’s Rake (http://rake.rubyforge.org)
holds the distinction of being the first
application that was available as a gem.
• % gem install -r rake
• % rake --version
• # gem install rails
Successfully installed activesupport-1.4.4
Successfully installed activerecord-1.15.5
Successfully installed actionpack-1.13.5
Successfully installed actionmailer-1.3.5
Successfully installed actionwebservice-1.2.5
Successfully installed rails-1.2.5
6 gems installed
• As you can see, the gem install command installs
the most recent version of the gem you request
and also installs any gems that the requested gem
requires
Common Gateway Interface (CGI)?
• Ruby is a universal language, not just the one
used in WEB development language, but Ruby
development in WEB applications and WEB tools
are the most common.
• Not only you can use Ruby to write your own
SMTP server, FTP program, or Ruby Web server,
but also can be use Ruby CGI programming.
• Let's take a moment to learn the Ruby CGI edited.
Web browsing
• To better understand how CGI works, we can click
on a link on a web page or URL of the process:
• 1, use your browser to access the URL and
connect to the HTTP web server.
• 2, Web server receives the request message will
be parsed URL and look accessed files on the
server if there is to return the contents of the file,
otherwise it returns an error message.
• 3, the browser receives the information from the
server and displays the received file or error
messages.
• CGI programs can be a Ruby script, Python script,
PERL script, SHELL script, C or C ++ programs.
• Web server configuration and support before
you conduct CGI programming, make sure that
your Web server has been configured to
support CGI and CGI handler.
• Apache supports CGI configuration:
• What is Common Gateway Interface (CGI)?
CGI is not a language. It’s a simple protocol
that can be used to communicate between
Web forms and your program.
• A CGI script can be written in any language
that can read STDIN, write to STDOUT, and
read environment variables, i.e. virtually any
programming language, including C, Perl, or
even shell scripting.
• It is identification for conveying data or
information between the World Wide Web
and a CGI program.
• CGI programs provide a dynamic way to
interact with the user and designed in a way
that they can accept and return data as well.
• All the processing occurs at the Web Server;
hence it is used as a Server-Side solution.
Structure of a CGI Script
• Here’s the typical sequence of steps for a CGI
script:
• 1. Read the user’s form input. When the user
submits the form, your script receives the form
data as a set of name-value pairs.
• The names are what you defined in the INPUT
tags (or SELECT or TEXTAREA tags), and the values
are whatever the user typed in or selected.
• 2. Do what you want with the data.
• 1 Write the HTML response to STDOUT.
• First, write the line
• Content-type: text/html plus another blank
line, to STDOUT.
• After that, write your HTML response page to
STDOUT, and it will be sent to the user when
your script is done. That’s all there is to it.
• Now, let us understand the way to write CGI
programs in Ruby.
• If you want to generate HTML output from a
Ruby script, you can write the following code:
print "HTTP/1.0 200 OKrn"
print "Content-type: text/htmlrnrn"
print"<html><body>Sucessfully
Registred</body></html>rn"
• Output
• HTTP/1.0 200 OK
• Content-type: text/html
• <html><body>Hello fella! Greetings from
IncludeHelp.com</body></html>
• cgi.rb is a predefined class termed as cgi helps
you to write CGI programs.
• You can create forms, cookies, maintain
stateful sessions and many more, with the
support of cgi class.
• You have to give the statement require cgi at
the top of the program to enjoy the
capabilities of cgi class.
• Quoting
• If are writing a URL or an HTML code, you are supposed to be very
careful with characters. Many characters have special meaning in
URLs. Translations of some of the characters are given below:
• / => %2F
• & => %26
• <space> => +
• To handle the above characters, cgi provides
you .escape and .unescape. They are routines of cgi. See the
example given below for reference:
require 'cgi'
puts CGI.escape( "He/She must be aware of his/her capabilities &
should work accordingly" )
• Output
He%2FShe+must+be+aware+of+his%2Fher+capabilities+%26+should+
work+accordingly
• he following code will let you know how you
can escape HTML special characters?
• require 'cgi'
• puts CGI.escapeHTML( '<a href="/san">Go to
the site(Includehelp.com)</a>' )
• Output
• &lt;a href=&quot;/san&quot;&gt;Go to the
site(Includehelp.com)&lt;/a&gt;
Creating forms and HTML
• cgi class is an umbrella of the huge number of
methods which are necessary to write HTML.
Every tag has got a method under cgi. cgi is a
class and we all that to access the methods of
a class, first we have to instantiate it. cgi can
be instantiated by calling CGI.new.
• Let us design a basic form with the help of
code mentioned below,
output
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.
• Most Tk-based applications follow the same cycle: create
the widgets, place them in the interface, and finally, bind
the events associated with each widget to a method.
• 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.
• Installation
• The Ruby Tk bindings are distributed with
Ruby but Tk is a separate installation.
Windows users can download a single click Tk
installation from ActiveState's ActiveTcl.
• Mac and Linux users may not need to install it
because there is a great chance that its
already installed along with OS but if not, you
can download prebuilt packages or get the
source from the Tcl Developer Xchange
• Simple Tk Application
• A typical structure for Ruby/Tk programs is to create the main or
root window (an instance of TkRoot), add widgets to it to build up
the user interface, and then start the main event loop by calling
Tk.mainloop.
• 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.
• TkFrame Creates and manipulates frame widgets.
• TkButton Creates and manipulates button widgets.
• TkLabel Creates and manipulates label widgets.
• TkEntry Creates and manipulates entry widgets.
• TkCheckButton Creates and manipulates checkbutton widgets.
• TkRadioButton Creates and manipulates radiobutton widgets.
• TkListbox Creates and manipulates listbox widgets.
• TkComboBox Creates and manipulates listbox widgets.
• TkMenu Creates and manipulates menu widgets.
• Ruby/TK – Frame Widget
• A frame is a widget that displays just as a
simple rectangle. Frames are primarily used as
a container for other widgets, which are under
the control of a geometry manager such as
grid.
• The only features of a frame are its
background color and an optional 3-D border
to make the frame appear raised or sunken.
• Ruby/Tk Geometry Management
• Geometry Management deals with positioning
different widgets as per requirement.
Geometry management in Tk relies on the
concept of master and slave widgets.
• A master is a widget, typically a top-level
window or a frame, which will contain other
widgets, which are called slaves. You can think
of a geometry manager as taking control of
the master widget, and deciding what will be
displayed within.
• The geometry manager will ask each slave widget for its natural
size, or how large it would ideally like to be displayed. It then takes
that information and combines it with any parameters provided by
the program when it asks the geometry manager to manage that
particular slave widget.
• 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.
• grid Geometry manager that arranges widgets in a grid.
• pack Geometry manager that packs around edges of cavity.
• place Geometry manager for fixed or rubber-sheet placement.
• Ruby/TK - The grid geometry manager
• The grid geometry manager is the most flexible and
easy-to-use geometry manager. It logically divides the
parent window or the widget into rows and columns in
a two-dimensional table.
• You can then place a widget in an appropriate row and
column format by using the row and column options,
respectively. To understand the use of row and column
options, consider the following example.
• 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'
• top = TkRoot.new {title "Label and Entry Widget"}
• #code to add a label widget
• lb1 = TkLabel.new(top){
• text 'Hello World'
• background "yellow"
• foreground "blue"
• grid('row'=>0, 'column'=>0)
• }
• #code to add a entry widget
• e1 = TkEntry.new(top){
• background "red"
• foreground "blue"
• grid('row’=>0, 'column'=>1)
• }
• 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.
• expand − The expand option is used to specify whether a widget should
expand to fill any extra space available. The default value is 0, which
means that the widget is not expanded. The other value is 1.
• 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 −
• pack('padx'=>10, 'pady'=>10, 'side'=>'left')
• require 'tk'
• top = TkRoot.new {title "Label and Entry Widget"}
• #code to add a label widget
• lb1 = TkLabel.new(top) {
• text 'Hello World'
• background "yellow"
• foreground "blue"
• pack('padx'=>10, 'pady'=>10, 'side'=>’l;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eft')
• }
• #code to add a entry widget
• e1 = TkEntry.new(top) {
• background "red"
• foreground "blue"
• pack('padx'=>10, 'pady'=>10, 'side'=>'left')
• }
• 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.
• To specify an absolute position, use the x and y
options. To specify a position relative to the
parent window or the widget, use the relx and
rely options.
• In addition, you can specify the relative size of
the widget by using the relwidth and relheight
options provided by this geometry manager.
• Syntax
• Here is a simple syntax to create a place
Widget −
• place(relx'=>x, 'rely'=>y)
• Examples
• Following is the code which implements the place geometry manager −
• require 'tk'
• top = TkRoot.new {title "Label and Entry Widget"}
• #code to add a label widget
• lb1 = TkLabel.new(top){
• text 'Hello World'
• background "yellow"
• foreground "blue"
• place('relx'=>0.0,'rely'=>0.0)
• }
• #code to add a entry widget
• e1 = TkEntry.new(top){
• background "red"
• foreground "blue"
• place('relx'=>0.4,'rely'=>0.0)
• }
• Tk.mainloop
• Ruby/TK - Canvas Widget
• A Canvas widget implements structured graphics. A canvas
displays any numberof items, which may be thingslike
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.
• thereare a widevariety ofdifferenttypes of itemsyou 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 −
• The TkcArc.new(canvas, x1, y1, x2, y2, ?option,
value, option, value, ...?) method will be used to
create an arc.
• The arguments x1, y1, x2, and y2 give the
coordinates of two diagonally opposite corners of
a rectangular region enclosing the oval that
defines the arc
• extent => degrees − Specifies the size of the angular range occupied by the arc. If it is greater
than 360 or less than -360, then degrees modulo 360 is used as the extent.
• 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: :
• The TkcImage.new(canvas,x, y, ?option, value,
option, value, ...?) method will be used to create
an image.
• The arguments x and y specify the coordinates of
a point used to position the image on the display.
• Here is the description of other options −
• anchor => anchorPos − AnchorPos tells how to position the
bitmap relative to the positioning point for the item. For
example, if anchorPos is center then the bitmap is centered
on the point; if anchorPos is n then the bitmap will be
drawn so that its top center point is at the positioning
point. This option defaults to center.
• image => name − Specifies the name of the image to
display in the item. This image must have been created
previously with the image create command.
• 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 −
• The TkcLine.new(canvas, x1, y1..., xn, yn, ?option,
value, ...?) method will be used to create a line.
• The arguments x1 through yn give the
coordinates for a series of two or more points
that describe a series of connected line segments.
• arrow => where − Indicates whether or not arrowheads are to be drawn at one or
both ends of the line. Where must have one of the values none (for no
arrowheads), first (for an arrowhead at the first point of the line), last (for an
arrowhead at the last point of the line), or both (for arrowheads at both ends).
This option defaults to none.
• arrowshape => shape − This option indicates how to draw arrowheads. If this
option isn't specified then Tk picks a reasonable shape.
• dash => pattern − Specifies a pattern to draw the line.
• capstyle => style − Specifies the ways in which caps are to be drawn at the
endpoints of the line. Possible values are butt, projecting, or round.
• fill => color − Color specifies a color to use for drawing the line.
• joinstyle => style − Specifies the ways in which joints are to be drawn at the
vertices of the line. Possible values are bevel, miter, or round.
• smooth => boolean − It indicates whether or not the line should be drawn as a
curve.
• splinesteps => number − Specifies the degree of smoothness desired for curves:
each spline will be approximated with number line segments. This option is
ignored unless the smooth option is true.
• width => lineWidth − Specifies the width of the line.
• Rectangle Items
• Items of type rectangle appear as rectangular
regions on the display. Each rectangle may have
an outline, a fill, or both. Rectangles are created
with methods of the following form −
• The TkcRectangle.new(canvas, x1, y1, x2, y2,
?option, value,...?) method will be used to create
a Rectangle.
• The arguments x1, y1, x2, and y2 give the
coordinates of two diagonally opposite corners of
the rectangle
• Here is the description of other options −
• fill => color − Fills the area of the rectangle with color.
• outline => color − Draws an outline around the edge of the
rectangle in color.
• stipple => bitmap − Indicates that the rectangle should be filled in a
stipple pattern; bitmap specifies the stipple pattern to use.
• 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 rectangle.
• Example 1
• 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
• 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.
• A scrollbar displays two arrows, one at each
end of the scrollbar, and a slider in the middle
portion of the scrollbar. The position and size
of the slider indicate which portion of the
document is visible in the associated window.
• Syntax
• Here is a simple syntax to create this widget −
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 −
• arrow1 − The top or left arrow in the scrollbar.
• trough1 − The region between the slider and arrow1.
• slider − The rectangle that indicates what is visible in
the associated widget.
• trough2 − The region between the slider and arrow2.
• arrow2 − The bottom or right arrow in the scrollbar.
• Manipulating the Listbox Items
• The insert idx item ?item... ? method is used to
add one or more items to the list; "idx" is a 0-
based index indicating the position of the item
before which the item(s) should be added;
specify "end" to put the new items at the end of
the list.
• The xview(args) method is used to query and
change the horizontal position of the information
in the widget's window.
• The yview(?args?) method is used to query and
change the vertical position of the text in the
widget's window.

More Related Content

What's hot

What's hot (20)

Perl names values and variables
Perl names values and variablesPerl names values and variables
Perl names values and variables
 
Beyond syllabus for web technology
Beyond syllabus for web technologyBeyond syllabus for web technology
Beyond syllabus for web technology
 
Design Model & User Interface Design in Software Engineering
Design Model & User Interface Design in Software EngineeringDesign Model & User Interface Design in Software Engineering
Design Model & User Interface Design in Software Engineering
 
Unified process model
Unified process modelUnified process model
Unified process model
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Java threads
Java threadsJava threads
Java threads
 
Loaders
LoadersLoaders
Loaders
 
ASP.NET - Life cycle of asp
ASP.NET - Life cycle of aspASP.NET - Life cycle of asp
ASP.NET - Life cycle of asp
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Php array
Php arrayPhp array
Php array
 
Java
JavaJava
Java
 
Types and roles
Types and rolesTypes and roles
Types and roles
 
Servlets
ServletsServlets
Servlets
 
Improving software econimics
Improving software econimicsImproving software econimics
Improving software econimics
 
Object Oriented Testing
Object Oriented TestingObject Oriented Testing
Object Oriented Testing
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web Development
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Client side scripting and server side scripting
Client side scripting and server side scriptingClient side scripting and server side scripting
Client side scripting and server side scripting
 

Similar to sl slides-unit-1.pptx

Top 10 programming languages
Top 10 programming languagesTop 10 programming languages
Top 10 programming languagesAman Kumar
 
The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189Mahmoud Samir Fayed
 
Programming Languages Categories / Programming Paradigm By: Prof. Lili Saghafi
Programming Languages Categories / Programming Paradigm By: Prof. Lili Saghafi Programming Languages Categories / Programming Paradigm By: Prof. Lili Saghafi
Programming Languages Categories / Programming Paradigm By: Prof. Lili Saghafi Professor Lili Saghafi
 
Ruby And Ruby On Rails
Ruby And Ruby On RailsRuby And Ruby On Rails
Ruby And Ruby On RailsAkNirojan
 
COMPUTER LANGUAGES AND THERE DIFFERENCE
COMPUTER LANGUAGES AND THERE DIFFERENCE COMPUTER LANGUAGES AND THERE DIFFERENCE
COMPUTER LANGUAGES AND THERE DIFFERENCE Pavan Kalyan
 
Top Programming Languages of 2020
Top Programming Languages of 2020Top Programming Languages of 2020
Top Programming Languages of 2020Ikbal Ahmed
 
The Ring programming language version 1.9 book - Part 6 of 210
The Ring programming language version 1.9 book - Part 6 of 210The Ring programming language version 1.9 book - Part 6 of 210
The Ring programming language version 1.9 book - Part 6 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 6 of 202
The Ring programming language version 1.8 book - Part 6 of 202The Ring programming language version 1.8 book - Part 6 of 202
The Ring programming language version 1.8 book - Part 6 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 6 of 196
The Ring programming language version 1.7 book - Part 6 of 196The Ring programming language version 1.7 book - Part 6 of 196
The Ring programming language version 1.7 book - Part 6 of 196Mahmoud Samir Fayed
 
Top programming Languages in software Industry companies
Top programming Languages in software Industry companiesTop programming Languages in software Industry companies
Top programming Languages in software Industry companiesKiran Patil
 
The Ring programming language version 1.2 book - Part 4 of 84
The Ring programming language version 1.2 book - Part 4 of 84The Ring programming language version 1.2 book - Part 4 of 84
The Ring programming language version 1.2 book - Part 4 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.4 book - Part 2 of 30
The Ring programming language version 1.4 book - Part 2 of 30The Ring programming language version 1.4 book - Part 2 of 30
The Ring programming language version 1.4 book - Part 2 of 30Mahmoud Samir Fayed
 
Julia Computing - an alternative to Hadoop
Julia Computing - an alternative to HadoopJulia Computing - an alternative to Hadoop
Julia Computing - an alternative to HadoopShaurya Shekhar
 
The Ring programming language version 1.5.2 book - Part 5 of 181
The Ring programming language version 1.5.2 book - Part 5 of 181The Ring programming language version 1.5.2 book - Part 5 of 181
The Ring programming language version 1.5.2 book - Part 5 of 181Mahmoud Samir Fayed
 

Similar to sl slides-unit-1.pptx (20)

Top 10 programming languages
Top 10 programming languagesTop 10 programming languages
Top 10 programming languages
 
Programming language
Programming languageProgramming language
Programming language
 
The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189The Ring programming language version 1.6 book - Part 6 of 189
The Ring programming language version 1.6 book - Part 6 of 189
 
Programming Languages Categories / Programming Paradigm By: Prof. Lili Saghafi
Programming Languages Categories / Programming Paradigm By: Prof. Lili Saghafi Programming Languages Categories / Programming Paradigm By: Prof. Lili Saghafi
Programming Languages Categories / Programming Paradigm By: Prof. Lili Saghafi
 
Ruby And Ruby On Rails
Ruby And Ruby On RailsRuby And Ruby On Rails
Ruby And Ruby On Rails
 
COMPUTER LANGUAGES AND THERE DIFFERENCE
COMPUTER LANGUAGES AND THERE DIFFERENCE COMPUTER LANGUAGES AND THERE DIFFERENCE
COMPUTER LANGUAGES AND THERE DIFFERENCE
 
02 ruby overview
02 ruby overview02 ruby overview
02 ruby overview
 
Top Programming Languages of 2020
Top Programming Languages of 2020Top Programming Languages of 2020
Top Programming Languages of 2020
 
The Ring programming language version 1.9 book - Part 6 of 210
The Ring programming language version 1.9 book - Part 6 of 210The Ring programming language version 1.9 book - Part 6 of 210
The Ring programming language version 1.9 book - Part 6 of 210
 
Computer programminglanguages
Computer programminglanguagesComputer programminglanguages
Computer programminglanguages
 
The Ring programming language version 1.8 book - Part 6 of 202
The Ring programming language version 1.8 book - Part 6 of 202The Ring programming language version 1.8 book - Part 6 of 202
The Ring programming language version 1.8 book - Part 6 of 202
 
The Ring programming language version 1.7 book - Part 6 of 196
The Ring programming language version 1.7 book - Part 6 of 196The Ring programming language version 1.7 book - Part 6 of 196
The Ring programming language version 1.7 book - Part 6 of 196
 
Top programming Languages in software Industry companies
Top programming Languages in software Industry companiesTop programming Languages in software Industry companies
Top programming Languages in software Industry companies
 
The Ring programming language version 1.2 book - Part 4 of 84
The Ring programming language version 1.2 book - Part 4 of 84The Ring programming language version 1.2 book - Part 4 of 84
The Ring programming language version 1.2 book - Part 4 of 84
 
Unit 1
Unit 1Unit 1
Unit 1
 
The Ring programming language version 1.4 book - Part 2 of 30
The Ring programming language version 1.4 book - Part 2 of 30The Ring programming language version 1.4 book - Part 2 of 30
The Ring programming language version 1.4 book - Part 2 of 30
 
Lecture 10
Lecture 10Lecture 10
Lecture 10
 
Xml & scripting
Xml & scriptingXml & scripting
Xml & scripting
 
Julia Computing - an alternative to Hadoop
Julia Computing - an alternative to HadoopJulia Computing - an alternative to Hadoop
Julia Computing - an alternative to Hadoop
 
The Ring programming language version 1.5.2 book - Part 5 of 181
The Ring programming language version 1.5.2 book - Part 5 of 181The Ring programming language version 1.5.2 book - Part 5 of 181
The Ring programming language version 1.5.2 book - Part 5 of 181
 

Recently uploaded

complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 

Recently uploaded (20)

complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 

sl slides-unit-1.pptx

  • 1. SCRIPTING LANGUAGES (Open Elective - III) 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.
  • 2. 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.
  • 3. 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.
  • 4. 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.
  • 5. 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.
  • 6. 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.
  • 7. • 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.
  • 8. • 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.
  • 9. 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.
  • 10. 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.
  • 11. • 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.
  • 12. 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.
  • 13. • 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.
  • 14. 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.
  • 15. 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.
  • 16. 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.
  • 17. 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
  • 18. 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!
  • 19. 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
  • 20. 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. And End Or Unless Begin Ensure reDo Until Break False Rescue When Case For Retry While Class If Return While Definse lf__FILE__ Defined ? Module Super __LINE__ BEGIN Do Next Then END Else Nil True Alias Elsif Not Undef
  • 21. 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 •
  • 22. 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.
  • 23. • 3.times { print "Ruby! " } # Prints "Ruby! Ruby! Ruby! " • • 1.upto(9) {|x| print x } # Prints "123456789"
  • 24. • 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.
  • 25. • Ruby vs Perl – Differences • Following are some of the basic differences of Ruby vs Perl: • 1. Development and Release • Perl programming language was developed by Larry Wall and released in the year of 1987. Ruby is a newcomer in the programming industry. And it was developed and released in 1995 by Yukihiro Matsumoto. • 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.
  • 26. • 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. • Objective-oriented programming stands for a physical model of programming execution. It simulates the behavior of either a real or imaginary part of the world. • The developer of Perl believes that choosing of OO should be the programmer’s decision; language should not force a programmer to switch to OO. • Ruby also doesn’t force you to choose an objective orientation, but if you do, it will be much easier to use than in Perl.
  • 27. 5. Supporting of Regular Expression • When we start a discussion on supporting of a regular expression, Perl has a very good number of libraries than Ruby has. The Perl library of code CPAN is incomparable with any other library. • So the supporting capacity of regular expression of Perl is little more than Ruby. But you need not worry as a user of Ruby, as it supports most of the regular expressions.
  • 28. • 8. Variable Type • Perl has multiple variable types like a scalar, array, hash, etc. in contrast, Ruby programming language offers only one variable type: reference to the object, the object can act like an array, hash, or whatever, depends on demand.
  • 29. • 9. Use of Sigils • Perl uses the sigils like @, $, and % to denote variable types. Ruby uses sigils such as @, @@, and $ to denote scope. To use all the variables in Perl except function, the user has to put some sigils. • But in the case of Ruby, there is no need for variables to work with local scopes.
  • 30. • 10. File Extension • A file extension is another major difference between Perl and Ruby. Perl programs have the .pl file extension while Ruby programs have the .rb file extension. • 11. Influenced Language • Perl is influenced by C, Basic, Lisp, Ada, etc. It mainly resembles with C language. On the other hand, Ruby is influenced by C, Perl, Smalltalk, Ada, Lisp, etc. Ruby has some additional touch from Smalltalk which is missing in Perl.
  • 31. • Conclusion • Perl is a quite old language, started its journey eight years ago than Ruby does. So, in the cases of community backup, availability of libraries for any need, documentation, Perl is far ahead of Ruby. Ruby has its merits in providing object- oriented features that help in keeping large code bodies maintainable. • So, both have some sort of merits and demerits. So, in the competition of Ruby vs Perl, the choice of language depends completely on the programmer.
  • 32. Ruby | Class & Object • In object-oriented programming classes and objects plays an important role. A class is a blueprint from which objects are created. The object is also called as an instance of a class. For Example, the animal is a class and mammals, birds, fish, reptiles, and amphibians are the instances of the class. Similarly, the sales department is the class and the objects of the class are sales data, sales manager, and secretary.
  • 33. Defining a class in Ruby: • In Ruby, one can easily create classes and objects. Simply write class keyword followed by the name of the class. The first letter of the class name should be in capital letter. Syntax: class Class_name end E.g: class Customer end
  • 34.
  • 35. • 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
  • 36.
  • 37. • 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.
  • 38.
  • 39. # Ruby program to illustrate # defining class Vehicle class GFG # defining method def geeks # printing result puts "Hello Geeks!" # end of method end # end of class GFG end # creating object obj = GFG.new # calling method using object obj.geeks • Output: • Hello Geeks! x=classname.new x.geeks
  • 40. • 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.
  • 41. • Syntax: class Class_Name def initialize(parameter_list) end end
  • 42. # class name class Demo # constructor def initialize puts "Welcome to GeeksforGeeks!" end end # Creating Obejct x= Demo.new • Output: • Welcome to GeeksforGeeks!
  • 43. 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
  • 44. • 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
  • 45. Ruby | Types of Variables • There are different types of variables in Ruby: • Local variables • Instance variables • Class variables • Global variables
  • 46. • 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
  • 47. • 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
  • 48. • 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.
  • 49. class Customer def initialize(id, name, addr) # Instance Variables @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 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() Output: Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya Customer id 2 Customer name Poul Customer address New Empire road, Khandala
  • 50. • 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.
  • 51. • 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
  • 52. 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
  • 53. 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.
  • 54. • 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.
  • 55. 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
  • 56. • 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.
  • 57. • =begin comments.rb author Jan Bodnar =end # prints message to the terminal puts "Comments example"
  • 58. 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.
  • 59. =begin Someone needs to fix the broken code below! Any code here is commented out =end
  • 60. • 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.
  • 61. x = 5 + 3 puts x y = 5 + 3 puts y z = 5 + 3 Puts z O/P: 8 5 8
  • 62. 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
  • 63. 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.
  • 64. • 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.
  • 65. • 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
  • 66. • Value • value2 • company_name These are valid variable names. • 12Val • exx$ • first-name These are examples of invalid variable names.
  • 67. • 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”
  • 68. 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
  • 69. • 2.4.3 Keywords • The following keywords have special meaning in Ruby and are treated specially by the Ruby parser:
  • 70. • 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 • ( ) [ ] { } , ; ' " | |
  • 71. • 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
  • 72. 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.
  • 73. • Ruby operators • An operator is a symbol used to perform an action on some value. (answers.com) • ! • + • - • ~ • * • ** • / • % • << >> • & | ^ == === != <=> >= > < <= = %= /= -= += *= **= .. ... not and or ?: • && ||
  • 74. • Ruby blocks • Ruby statements are often organized into blocks of code. A code block can be delimited using { } characters or do and end keywords.
  • 75. • 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
  • 76. • 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.
  • 77. • 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.
  • 78. 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
  • 79. • 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
  • 80. • 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:
  • 81. if x < 10 then # If this expression is true x = x + 1 # Then execute this statement end # Marks the end of the conditional
  • 82. • 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
  • 83. 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! " }
  • 84. 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
  • 85. • #!/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
  • 86. 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
  • 87. • 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.
  • 88. • 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.
  • 89. Ruby if...else Statement if conditional [then] code... [elsif conditional [then] code...]... [else code...] end
  • 90. 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
  • 91. 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
  • 92. $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
  • 93. • Ruby for Statement • Syntax for variable [, variable ...] in expression [do] code end
  • 94. 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++)
  • 95. • 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
  • 96. • 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.
  • 97. 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.
  • 98. • 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.
  • 99. • 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.
  • 100. • 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.
  • 101. 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:
  • 102. • If you see a gem you want more information on you can add the details option.
  • 103. • INSTALLING GEMS • The install command downloads and installs the gem and any necessary dependencies then builds documentation for the installed gems.
  • 104. • 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
  • 105. • UNINSTALLING GEMS • The uninstall command removes the gems you have installed.
  • 106. STRUCTURE OF A GEM • each gem has a name, version, and platform. For example, the rake gem has a 0.8.7 version (from May, 2009). Rake’s platform is ruby, which means it works on any platform Ruby runs on.
  • 107. • Platforms are based on the CPU architecture, operating system type and sometimes the operating system version. Examples include “x86-mingw32” or “java”. The platform indicates the gem only works with a ruby built for the same platform. • RubyGems will automatically download the correct version for your platform. See gem help platform for full details.
  • 108. • Inside gems are the following components: • Code (including tests and supporting utilities) • Documentation • gemspec
  • 109. • THE GEMSPEC • The gemspec specifies the information about a gem such as its name, version, description, authors and homepage.
  • 110. The lib directory contains the code for the gem The test or spec directory contains tests, depending on which test framework the developer uses A gem usually has a Rakefile, which the rake program uses to automate tests, generate code, and perform other tasks. This gem also includes an executable file in the bin directory, which will be loaded into the user’s PATH when the gem is installed. Documentation is usually included in the README and inline with the code. When you install a gem, documentation is generated automatically for you. Most gems include RDoc documentation
  • 111. • In this chapter, we’ll see how to • 1. Install RubyGems on your computer. • 2. Use RubyGems to install other applications and libraries. • 3. Write your own gems.
  • 112. Installing RubyGems • To use RubyGems, you’ll first need to download and install the RubyGems system from the project’s home page at http://rubygems.rubyforge.org • % cd rubygems0.7.0 • % ruby install.rb
  • 113. • The best way to test that RubyGems was installed successfully also happens to be the • most important command you’ll learn. • % gem help
  • 114. Installing Application Gems • Let’s start by using RubyGems to install an application that is written in Ruby. Jim Weirich’s Rake (http://rake.rubyforge.org) holds the distinction of being the first application that was available as a gem. • % gem install -r rake • % rake --version
  • 115. • # gem install rails Successfully installed activesupport-1.4.4 Successfully installed activerecord-1.15.5 Successfully installed actionpack-1.13.5 Successfully installed actionmailer-1.3.5 Successfully installed actionwebservice-1.2.5 Successfully installed rails-1.2.5 6 gems installed • As you can see, the gem install command installs the most recent version of the gem you request and also installs any gems that the requested gem requires
  • 116. Common Gateway Interface (CGI)? • Ruby is a universal language, not just the one used in WEB development language, but Ruby development in WEB applications and WEB tools are the most common. • Not only you can use Ruby to write your own SMTP server, FTP program, or Ruby Web server, but also can be use Ruby CGI programming. • Let's take a moment to learn the Ruby CGI edited.
  • 117. Web browsing • To better understand how CGI works, we can click on a link on a web page or URL of the process: • 1, use your browser to access the URL and connect to the HTTP web server. • 2, Web server receives the request message will be parsed URL and look accessed files on the server if there is to return the contents of the file, otherwise it returns an error message. • 3, the browser receives the information from the server and displays the received file or error messages. • CGI programs can be a Ruby script, Python script, PERL script, SHELL script, C or C ++ programs.
  • 118.
  • 119. • Web server configuration and support before you conduct CGI programming, make sure that your Web server has been configured to support CGI and CGI handler. • Apache supports CGI configuration:
  • 120. • What is Common Gateway Interface (CGI)? CGI is not a language. It’s a simple protocol that can be used to communicate between Web forms and your program. • A CGI script can be written in any language that can read STDIN, write to STDOUT, and read environment variables, i.e. virtually any programming language, including C, Perl, or even shell scripting.
  • 121. • It is identification for conveying data or information between the World Wide Web and a CGI program. • CGI programs provide a dynamic way to interact with the user and designed in a way that they can accept and return data as well. • All the processing occurs at the Web Server; hence it is used as a Server-Side solution.
  • 122. Structure of a CGI Script • Here’s the typical sequence of steps for a CGI script: • 1. Read the user’s form input. When the user submits the form, your script receives the form data as a set of name-value pairs. • The names are what you defined in the INPUT tags (or SELECT or TEXTAREA tags), and the values are whatever the user typed in or selected. • 2. Do what you want with the data.
  • 123. • 1 Write the HTML response to STDOUT. • First, write the line • Content-type: text/html plus another blank line, to STDOUT. • After that, write your HTML response page to STDOUT, and it will be sent to the user when your script is done. That’s all there is to it.
  • 124. • Now, let us understand the way to write CGI programs in Ruby. • If you want to generate HTML output from a Ruby script, you can write the following code: print "HTTP/1.0 200 OKrn" print "Content-type: text/htmlrnrn" print"<html><body>Sucessfully Registred</body></html>rn"
  • 125. • Output • HTTP/1.0 200 OK • Content-type: text/html • <html><body>Hello fella! Greetings from IncludeHelp.com</body></html>
  • 126. • cgi.rb is a predefined class termed as cgi helps you to write CGI programs. • You can create forms, cookies, maintain stateful sessions and many more, with the support of cgi class. • You have to give the statement require cgi at the top of the program to enjoy the capabilities of cgi class.
  • 127. • Quoting • If are writing a URL or an HTML code, you are supposed to be very careful with characters. Many characters have special meaning in URLs. Translations of some of the characters are given below: • / => %2F • & => %26 • <space> => + • To handle the above characters, cgi provides you .escape and .unescape. They are routines of cgi. See the example given below for reference: require 'cgi' puts CGI.escape( "He/She must be aware of his/her capabilities & should work accordingly" ) • Output He%2FShe+must+be+aware+of+his%2Fher+capabilities+%26+should+ work+accordingly
  • 128. • he following code will let you know how you can escape HTML special characters? • require 'cgi' • puts CGI.escapeHTML( '<a href="/san">Go to the site(Includehelp.com)</a>' ) • Output • &lt;a href=&quot;/san&quot;&gt;Go to the site(Includehelp.com)&lt;/a&gt;
  • 129. Creating forms and HTML • cgi class is an umbrella of the huge number of methods which are necessary to write HTML. Every tag has got a method under cgi. cgi is a class and we all that to access the methods of a class, first we have to instantiate it. cgi can be instantiated by calling CGI.new.
  • 130. • Let us design a basic form with the help of code mentioned below,
  • 131. output 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.
  • 132. 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.
  • 133. #!/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 }
  • 134. • 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.
  • 135. • 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. • Most Tk-based applications follow the same cycle: create the widgets, place them in the interface, and finally, bind the events associated with each widget to a method. • 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.
  • 136. • Installation • The Ruby Tk bindings are distributed with Ruby but Tk is a separate installation. Windows users can download a single click Tk installation from ActiveState's ActiveTcl. • Mac and Linux users may not need to install it because there is a great chance that its already installed along with OS but if not, you can download prebuilt packages or get the source from the Tcl Developer Xchange
  • 137. • Simple Tk Application • A typical structure for Ruby/Tk programs is to create the main or root window (an instance of TkRoot), add widgets to it to build up the user interface, and then start the main event loop by calling Tk.mainloop. • 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
  • 138. • 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. • TkFrame Creates and manipulates frame widgets. • TkButton Creates and manipulates button widgets. • TkLabel Creates and manipulates label widgets. • TkEntry Creates and manipulates entry widgets. • TkCheckButton Creates and manipulates checkbutton widgets. • TkRadioButton Creates and manipulates radiobutton widgets. • TkListbox Creates and manipulates listbox widgets. • TkComboBox Creates and manipulates listbox widgets. • TkMenu Creates and manipulates menu widgets.
  • 139. • Ruby/TK – Frame Widget • A frame is a widget that displays just as a simple rectangle. Frames are primarily used as a container for other widgets, which are under the control of a geometry manager such as grid. • The only features of a frame are its background color and an optional 3-D border to make the frame appear raised or sunken.
  • 140.
  • 141. • Ruby/Tk Geometry Management • Geometry Management deals with positioning different widgets as per requirement. Geometry management in Tk relies on the concept of master and slave widgets. • A master is a widget, typically a top-level window or a frame, which will contain other widgets, which are called slaves. You can think of a geometry manager as taking control of the master widget, and deciding what will be displayed within.
  • 142. • The geometry manager will ask each slave widget for its natural size, or how large it would ideally like to be displayed. It then takes that information and combines it with any parameters provided by the program when it asks the geometry manager to manage that particular slave widget. • 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. • grid Geometry manager that arranges widgets in a grid. • pack Geometry manager that packs around edges of cavity. • place Geometry manager for fixed or rubber-sheet placement.
  • 143. • Ruby/TK - The grid geometry manager • The grid geometry manager is the most flexible and easy-to-use geometry manager. It logically divides the parent window or the widget into rows and columns in a two-dimensional table. • You can then place a widget in an appropriate row and column format by using the row and column options, respectively. To understand the use of row and column options, consider the following example. • Syntax • Here is a simple syntax to create a grid Widget − • grid('row'=>x, 'column'=>y)
  • 144. • Examples • Following is the code to display the Label and an Entry widget using the grid geometry manager − • require 'tk' • top = TkRoot.new {title "Label and Entry Widget"} • #code to add a label widget • lb1 = TkLabel.new(top){ • text 'Hello World' • background "yellow" • foreground "blue" • grid('row'=>0, 'column'=>0) • } • #code to add a entry widget • e1 = TkEntry.new(top){ • background "red" • foreground "blue" • grid('row’=>0, 'column'=>1) • } • Tk.mainloop
  • 145. • 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. • expand − The expand option is used to specify whether a widget should expand to fill any extra space available. The default value is 0, which means that the widget is not expanded. The other value is 1. • 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.
  • 146. • Syntax • Here is a simple syntax to create a pack Widget − • pack('padx'=>10, 'pady'=>10, 'side'=>'left')
  • 147. • require 'tk' • top = TkRoot.new {title "Label and Entry Widget"} • #code to add a label widget • lb1 = TkLabel.new(top) { • text 'Hello World' • background "yellow" • foreground "blue" • pack('padx'=>10, 'pady'=>10, 'side'=>’l;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eft') • } • #code to add a entry widget • e1 = TkEntry.new(top) { • background "red" • foreground "blue" • pack('padx'=>10, 'pady'=>10, 'side'=>'left') • } • Tk.mainloop
  • 148. • 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. • To specify an absolute position, use the x and y options. To specify a position relative to the parent window or the widget, use the relx and rely options. • In addition, you can specify the relative size of the widget by using the relwidth and relheight options provided by this geometry manager.
  • 149. • Syntax • Here is a simple syntax to create a place Widget − • place(relx'=>x, 'rely'=>y)
  • 150. • Examples • Following is the code which implements the place geometry manager − • require 'tk' • top = TkRoot.new {title "Label and Entry Widget"} • #code to add a label widget • lb1 = TkLabel.new(top){ • text 'Hello World' • background "yellow" • foreground "blue" • place('relx'=>0.0,'rely'=>0.0) • } • #code to add a entry widget • e1 = TkEntry.new(top){ • background "red" • foreground "blue" • place('relx'=>0.4,'rely'=>0.0) • } • Tk.mainloop
  • 151. • Ruby/TK - Canvas Widget • A Canvas widget implements structured graphics. A canvas displays any numberof items, which may be thingslike rectangles, circles, lines, and text. • Syntax TkCanvas.new { .....Standard Options.... .....Widget-specific Options.... }
  • 152. 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. • thereare a widevariety ofdifferenttypes of itemsyou can add • Arc Items • Bitmap Items • Image Items • Line Items • Rectangle Items
  • 153. • 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 − • The TkcArc.new(canvas, x1, y1, x2, y2, ?option, value, option, value, ...?) method will be used to create an arc. • The arguments x1, y1, x2, and y2 give the coordinates of two diagonally opposite corners of a rectangular region enclosing the oval that defines the arc
  • 154. • extent => degrees − Specifies the size of the angular range occupied by the arc. If it is greater than 360 or less than -360, then degrees modulo 360 is used as the extent. • 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.
  • 155. • Image Items • Items of type image are used to display images on a canvas. Images are created with methods of the following form: : • The TkcImage.new(canvas,x, y, ?option, value, option, value, ...?) method will be used to create an image. • The arguments x and y specify the coordinates of a point used to position the image on the display.
  • 156. • Here is the description of other options − • anchor => anchorPos − AnchorPos tells how to position the bitmap relative to the positioning point for the item. For example, if anchorPos is center then the bitmap is centered on the point; if anchorPos is n then the bitmap will be drawn so that its top center point is at the positioning point. This option defaults to center. • image => name − Specifies the name of the image to display in the item. This image must have been created previously with the image create command. • 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.
  • 157. • 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 − • The TkcLine.new(canvas, x1, y1..., xn, yn, ?option, value, ...?) method will be used to create a line. • The arguments x1 through yn give the coordinates for a series of two or more points that describe a series of connected line segments.
  • 158. • arrow => where − Indicates whether or not arrowheads are to be drawn at one or both ends of the line. Where must have one of the values none (for no arrowheads), first (for an arrowhead at the first point of the line), last (for an arrowhead at the last point of the line), or both (for arrowheads at both ends). This option defaults to none. • arrowshape => shape − This option indicates how to draw arrowheads. If this option isn't specified then Tk picks a reasonable shape. • dash => pattern − Specifies a pattern to draw the line. • capstyle => style − Specifies the ways in which caps are to be drawn at the endpoints of the line. Possible values are butt, projecting, or round. • fill => color − Color specifies a color to use for drawing the line. • joinstyle => style − Specifies the ways in which joints are to be drawn at the vertices of the line. Possible values are bevel, miter, or round. • smooth => boolean − It indicates whether or not the line should be drawn as a curve. • splinesteps => number − Specifies the degree of smoothness desired for curves: each spline will be approximated with number line segments. This option is ignored unless the smooth option is true. • width => lineWidth − Specifies the width of the line.
  • 159. • Rectangle Items • Items of type rectangle appear as rectangular regions on the display. Each rectangle may have an outline, a fill, or both. Rectangles are created with methods of the following form − • The TkcRectangle.new(canvas, x1, y1, x2, y2, ?option, value,...?) method will be used to create a Rectangle. • The arguments x1, y1, x2, and y2 give the coordinates of two diagonally opposite corners of the rectangle
  • 160. • Here is the description of other options − • fill => color − Fills the area of the rectangle with color. • outline => color − Draws an outline around the edge of the rectangle in color. • stipple => bitmap − Indicates that the rectangle should be filled in a stipple pattern; bitmap specifies the stipple pattern to use. • 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 rectangle.
  • 161. • Example 1 • 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
  • 162. • 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. • A scrollbar displays two arrows, one at each end of the scrollbar, and a slider in the middle portion of the scrollbar. The position and size of the slider indicate which portion of the document is visible in the associated window.
  • 163. • Syntax • Here is a simple syntax to create this widget − TkScrollbar.new { .....Standard Options.... .....Widget-specific Options.... }
  • 164. • 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
  • 165. • Elements of Scrollbar • A scrollbar displays five elements, which are referred in the methods for the scrollbar − • arrow1 − The top or left arrow in the scrollbar. • trough1 − The region between the slider and arrow1. • slider − The rectangle that indicates what is visible in the associated widget. • trough2 − The region between the slider and arrow2. • arrow2 − The bottom or right arrow in the scrollbar.
  • 166. • Manipulating the Listbox Items • The insert idx item ?item... ? method is used to add one or more items to the list; "idx" is a 0- based index indicating the position of the item before which the item(s) should be added; specify "end" to put the new items at the end of the list. • The xview(args) method is used to query and change the horizontal position of the information in the widget's window. • The yview(?args?) method is used to query and change the vertical position of the text in the widget's window.