0% found this document useful (0 votes)
27 views113 pages

SL Unit 1

The document provides an overview of Ruby, a dynamic, object-oriented scripting language, detailing its features, syntax, and execution structure. It covers topics such as Ruby on Rails, variable types, and the language's design philosophy, emphasizing its community and ecosystem. Additionally, it explains Ruby's syntax, including comments, literals, identifiers, and keywords, making it a comprehensive guide for understanding Ruby programming.

Uploaded by

UMADEVI AVULA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views113 pages

SL Unit 1

The document provides an overview of Ruby, a dynamic, object-oriented scripting language, detailing its features, syntax, and execution structure. It covers topics such as Ruby on Rails, variable types, and the language's design philosophy, emphasizing its community and ecosystem. Additionally, it explains Ruby's syntax, including comments, literals, identifiers, and keywords, making it a comprehensive guide for understanding Ruby programming.

Uploaded by

UMADEVI AVULA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

Scripting Languages

Unit I
By
Ms S.Rama Devi
Associate Professor
Department of Information Technology

BVRIT HYDERABAD College of Engineering for Women


Contents
• 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.

BVRIT HYDERABAD College of Engineering for Women


Ruby
1. Object-Oriented: Everything in Ruby is an object, which allows for a more organized and modular
code structure.
2. Dynamic Typing: Ruby is dynamically typed, meaning that variable types are determined at runtime
rather than at compile time. This can make development faster and more flexible but may also
introduce potential runtime errors.
3. Garbage Collection: Ruby has automatic memory management through garbage collection, which
helps developers focus more on writing code rather than managing memory.
4. Rich Standard Library: Ruby comes with a comprehensive standard library that provides a wide
range of built-in classes and modules for common programming tasks.
5. Community and Ecosystem: Ruby has a vibrant and active community, with numerous libraries
(gems) available through the RubyGems package manager. The Ruby community values convention
over configuration, which has led to the development of frameworks and tools that emphasize best
practices and productivity.
6. Ruby on Rails: Ruby gained significant popularity with the introduction of the Ruby on Rails web
framework, which is designed to make web application development faster and more straightforward.
Rails follows the "Convention over Configuration" and "Don't Repeat Yourself" (DRY) principles, which
have contributed to its popularity among developers.

BVRIT HYDERABAD College of Engineering for Women


What is Ruby?
• Originally conceived by Yukihiro Matsumoto
– February 24, 1993, Japan
• first public release in 1995
• Feb 24, 2013: Ruby 2.0 release
– motivation:
• “wanted a scripting language [...] more powerful than Perl, and more
object-oriented than Python”
• wanted a natural and very expressive language in which programmers can
easily express themselves
– language named after a precious gemstone
• à la “Perl”
– is an open source project

BVRIT HYDERABAD College of Engineering for Women


• Ruby is an interpreted, object-oriented, dynamically typed
programming language with strong reflective and scripting facilities
– Compact syntax inspired by Python and Perl
– Semantics akin to dynamically class-based languages like Smalltalk
– Scripting facilities akin to those of Python and Perl
• manipulation of text files
• file handling
• execution of system tasks
• support for regular expressions

BVRIT HYDERABAD College of Engineering for Women


Why Ruby?

• Because:
• Pure object-oriented language
• Interesting, not entirely obvious implications
• Interesting design decisions (compare Java)
• Particularly type system, mixins, etc.
• Interesting, but not our focus
• Scripting language
• RAILS and other frameworks

BVRIT HYDERABAD College of Engineering for Women


Ruby’s “killer app”

• Ruby on Rails (a.k.a. “Rails” or “RoR”)


– Open-source web-application framework
– Implemented in Ruby
– Allows you to quickly create powerful web applications
– Based on model-view-controller pattern
– Web-application =
• Ruby program + database + webserver

BVRIT HYDERABAD College of Engineering for Women


Ruby’s language features
• Purely object-oriented (everything is an object)
• Dynamically typed
• Message passing is only control-structure
• Single class based inheritance
• Automatic garbage collection
• Exception handling
• First-class closures (blocks)
• Reflective facilities
• Features for program evolution (e.g., mixins)
• Embedded scripting facilities (e.g. regular expressions)
• In addition, it comes with a large standard library

BVRIT HYDERABAD College of Engineering for Women


Ruby
• A dynamic programming language with a complex
but expressive grammar and a core class library with
a rich and powerful API.
• Draws inspiration from Lisp, Smalltalk, and Perl, but
uses a grammar that is easy for C and Java™
programmers to learn.
• A pure object-oriented language, but it is also
suitable for procedural and functional programming
styles.
• It includes powerful metaprogramming capabilities
and can be used to create domain-specific languages
or DSLs.

BVRIT HYDERABAD College of Engineering for Women


Ruby Is Object-Oriented

• 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).

• Comments begin with # in Ruby, and the => arrows in the comments
indicate the value returned by the commented code

BVRIT HYDERABAD College of Engineering for Women


Industries Where Flagship Companies Use Ruby on Rails

BVRIT HYDERABAD College of Engineering for Women


Syntax Of Ruby
• All ruby files will have extension .rb

Example:
#!/usr/bin/ruby –w
puts "Hello, Ruby!";

• Run this program as follows


$ ruby test.rb

BVRIT HYDERABAD College of Engineering for Women


Variables
• Global variables begin with $. Uninitialized global variables have the
value nil and produce warnings with the -w option.
• Assignment to global variables alters the global status. It is not recommended
to use global variables.
• They make programs cryptic.

• Instance variables begin with @. Uninitialized instance variables have


the value nil and produce warnings with the -w option.

BVRIT HYDERABAD College of Engineering for Women


# global variable
$global_variable = 10

# Defining class
class Class1
def print_global
puts "Global variable in Class1 is #$global_variable"
end
end
• Class variables begin with @@ and must be initialized before they
can be used in method definitions. Referencing an uninitialized class
variable produces an error.
• Class variables are shared among descendants of the class or module in which
the class variables are defined.
• Overriding class variables produce warnings with the -w option.

BVRIT HYDERABAD College of Engineering for Women


• Local variables begin with a lowercase letter or _. The scope of a
local variable ranges from class, module, def, or do to the
corresponding end or from a block's opening brace to its close brace
{}.
• When an uninitialized local variable is referenced, it is interpreted as a call to
a method that has no arguments.
• Assignment to uninitialized local variables also serves as variable declaration.
• The variables start to exist until the end of the current scope is reached.
• The lifetime of local variables is determined when Ruby parses the program.

BVRIT HYDERABAD College of Engineering for Women


Ruby Constants

• Constants begin with an uppercase letter.


• Constants defined within a class or module can be accessed from
within that class or module, and those defined outside a class or
module can be accessed globally.
• Constants may not be defined within methods. Referencing an
uninitialized constant produces an error.
• Making an assignment to a constant that is already initialized
produces a warning.

BVRIT HYDERABAD College of Engineering for Women


The Structure and Execution of Ruby Programs
Lexical Structure
• The Ruby interpreter parses a program as a sequence of tokens.

• Tokens include comments, literals, punctuation, identifiers, and


keywords.

BVRIT HYDERABAD College of Engineering for Women


Comments
• Comments 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).
• If a # character appears within a string or regular expression literal,
then it is simply part of the string or regular expression and does not
introduce a comment:
• # This entire line is a comment
x = "#This is a string" # And this is a comment
y = /#This is a regular expression/ # Here's another comment

BVRIT HYDERABAD College of Engineering for Women


• 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: Ruby has no equivalent of the C-style /*...*/ comment.
• There is no way to embed a comment in the middle of a line of code.

BVRIT HYDERABAD College of Engineering for Women


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.

BVRIT HYDERABAD College of Engineering for Women


• Embedded documents are a convenient way to comment out long blocks
of code without prefixing each line with a # character:
=begin Someone needs to fix the broken code below!
Any code here is commented out
=end
• Note: embedded documents only work if the = signs are the first
characters of each line:
# =begin This used to begin a comment. Now it is itself commented
out!
The code that goes here is no longer commented out
# =end

BVRIT HYDERABAD College of Engineering for Women


Documentation comments
• Ruby programs can include embedded API documentation as specially
formatted comments that precede method, class, and module
definitions.
• The rdoc tool extracts documentation comments from Ruby source and
formats them as HTML or prepares them for display by ri.
• Documentation comments must come immediately before the module,
class, or method whose API they document.
• They are usually written as multiline comments where each line begins
with #, but they can also be written as embedded documents that start
=begin rdoc. (The rdoc tool will not process these comments if you
leave out the “rdoc”.)

BVRIT HYDERABAD College of Engineering for Women


Literals
• Literals are values that appear directly in Ruby source code.
• They include numbers, strings of text, and regular expressions. (Other
literals, such as array and hash values, are not individual tokens but
are more complex expressions.) Ruby number and string literal syntax
is actually quite complicated.
• An example suffices to illustrate what Ruby literals look like:
1 # An integer literal
1.0 # A floating-point literal
'one’ # A string literal
"two“ # Another string literal
/three/ # A regular expression literal

BVRIT HYDERABAD College of Engineering for Women


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.
• Punctuation characters also serve to delimit string, regular
expression, array, and hash literals, and to group and separate
expressions, method arguments, and array indexes.
• Miscellaneous other uses of punctuation scattered throughout Ruby
syntax.

BVRIT HYDERABAD College of Engineering for Women


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 or nonprinting characters, and
they may not include punctuation characters.
• 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.

BVRIT HYDERABAD College of Engineering for Women


• 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.

BVRIT HYDERABAD College of Engineering for Women


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.

BVRIT HYDERABAD College of Engineering for Women


Punctuation in identifiers
Punctuation characters may appear at the start and end of Ruby identifiers.
They have the following meanings:

• $ Global variables are prefixed with a dollar sign. Ruby defines a number
of global variables that include other punctuation characters, such as $_
and $-K.
• @ Instance variables are prefixed with a single at sign, and class variables
are prefixed with two at signs.
• ? As a helpful convention, methods that return Boolean values often have
names that end with a question mark.

BVRIT HYDERABAD College of Engineering for Women


• ! Method names may end with an exclamation point to indicate that
they should be used cautiously.
• This naming convention is often to distinguish mutator methods that alter
the object on which they are invoked from variants that return a modified
copy of the original object.

• = Methods whose names end with an equals sign can be invoked by


placing the method name, without the equals sign, on the left side of
an assignment operator.

BVRIT HYDERABAD College of Engineering for Women


• 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

BVRIT HYDERABAD College of Engineering for Women


Keywords
• The following keywords have special meaning in Ruby and are treated specially by
the Ruby parser:
__LINE__ case ensure not then
__ENCODING__ class false or true
__FILE__ def for redo undef
BEGIN defined? if rescue unless
END do in retry until
alias else module return when
and elsif next self while
begin end nil super yield
break

BVRIT HYDERABAD College of Engineering for Women


Whitespace
• Spaces, tabs, and newlines are not tokens themselves but are used to
separate tokens that would otherwise merge into a single token.
• Most whitespace is ignored by the Ruby interpreter and is simply used
to format programs so that they are easy to read and understand.
• Not all whitespace is ignored. Some is required, and some whitespace is
actually forbidden.
• Ruby’s grammar is expressive but complex, and there are a few cases in
which inserting or removing whitespace can change the meaning of a
program.
• Although these cases do not often arise, it is important to know about
them.

BVRIT HYDERABAD College of Engineering for Women


Newlines as statement terminators
• The most common form of whitespace dependency has to do with newlines as
statement terminators.
• In languages like C and Java, every statement must be terminated with a
semicolon.
• Use semicolons to terminate statements in Ruby, too, but this is only
required if you put more than one statement on the same line.
• Convention dictates that semicolons be omitted elsewhere.
• Without explicit semicolons, the Ruby interpreter must figure out on its own
where statements end.
• If the Ruby code on a line is a syntactically complete statement, Ruby uses the
newline as the statement terminator.
• If the statement is not complete, then Ruby continues parsing the statement
on the next line.

BVRIT HYDERABAD College of Engineering for Women


• This is no problem if all your statements fit on a single line.
• When they don’t, however, you must take care that you break the line in such
a way that the Ruby interpreter cannot interpret the first line as a statement
of its own.
• This is where the whitespace dependency lies: your program may behave
differently depending on where you insert a newline.
• For example, the following code adds x and y and assigns the sum to total:
total = x + # Incomplete expression, parsing continues
y
• But this code assigns x to total, and then evaluates y, doing nothing with it:
total = x # This is a complete expression
+y # A useless but complete expression

BVRIT HYDERABAD College of Engineering for Women


Syntactic Structure
• The basic unit of syntax in Ruby is the expression.
• The Ruby interpreter evaluates expressions, producing values.
• The simplest expressions are primary expressions, which represent values
directly.
• Number and string literals, are primary expressions.
• Other primary expressions include certain keywords such as true, false,
nil, and self.
• Variable references are also primary expressions; they evaluate to the
value of the variable.

BVRIT HYDERABAD College of Engineering for Women


• 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

BVRIT HYDERABAD College of Engineering for Women


Block Structure in Ruby
• Ruby programs have a block structure.
• 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

BVRIT HYDERABAD College of Engineering for Women


3.times { print "Ruby! " }
• In this code, the curly braces and the code inside them are the block
associated with the iterator method invocation 3.times.
• Formal blocks of this kind may be delimited with curly braces, or they
may be delimited with the keywords do and end:
1.upto(10) do |x|
print x
end
• do and end delimiters are usually used when the block is written on
more than one line.
• Note the two-space indentation of the code within the block

BVRIT HYDERABAD College of Engineering for Women


• Bodies and blocks can be nested within each other, and Ruby programs typically
have several levels of nested code, made readable by their relative indentation.
• Here is a schematic example:
module Stats # A module
class Dataset # A class in the module
def initialize(filename) # A method in the class
IO.foreach(filename) do |line| # A block in the method
if line[0,1] == "#" # An if statement in the block
next # A simple statement in the if
end # End the if body
end # End the block
end # End the method body
end # End the class body
end # End the module body

BVRIT HYDERABAD College of Engineering for Women


File Structure
• There are only a few rules about how a file of Ruby code must be
structured related to the deployment of Ruby programs and are not directly
relevant to the language itself.
• First, if a Ruby program contains a “shebang” comment, to tell the
operating system how to execute it, that comment must appear on the first
line.
• Second, if a Ruby program contains a “coding” comment 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.
BVRIT HYDERABAD College of Engineering for Women
• Ruby programs are not required to fit in a single file. Many programs load
additional Ruby code from external libraries.
• Programs use require to load code from another file. require searches for
specified modules of code against a search path, and prevents any given
module from being loaded more than once.
• The following code illustrates each of these points of Ruby file structure:
#!/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

(UCS)Unicode Transformation Format". The UTF-8 encoding can be used to represent


any Unicode character numeric value
*UCS- unified computing system

BVRIT HYDERABAD College of Engineering for Women


Program Encoding
• At the lowest level, a Ruby program is simply a sequence of
characters.
• Ruby’s lexical rules are defined using characters of the ASCII character
set.
• Comments begin with the # character (ASCII code 35), for example,
and allowed whitespace characters are horizontal tab (ASCII 9),
newline (10), vertical tab (11), form feed (12), carriage return (13),
and space (32).
• All Ruby keywords are written using ASCII characters, and all
operators and other punctuation are drawn from the ASCII character
set.

BVRIT HYDERABAD College of Engineering for Women


• By default, the Ruby interpreter assumes that Ruby source code is
encoded in ASCII.
• The interpreter can also process files that use other encodings, as
long as those encodings can represent the full set of ASCII characters.
• In order for the Ruby interpreter to be able to interpret the bytes of a
source file as characters, it must know what encoding to use. Ruby
files can identify their own encodings or you can tell the interpreter
how they are encoded.
• The Ruby interpreter is actually quite flexible about the characters
that appear in a Ruby program. Certain ASCII characters have specific
meanings, and certain ASCII characters are not allowed in identifiers,
but beyond that, a Ruby program may contain any characters allowed
by the encoding.

BVRIT HYDERABAD College of Engineering for Women


• In ASCII-encoded files, strings may include arbitrary bytes, including
those that represent nonprinting control characters. (Using raw bytes
like this is not recommended, however; Ruby string literals support
escape sequences so that arbitrary characters can be included by
numeric code instead.)
• If the file is written using the UTF-8 encoding, then comments,
strings, and regular expressions may include arbitrary Unicode
characters.

BVRIT HYDERABAD College of Engineering for Women


Specifying Program Encoding
• By default, the Ruby interpreter assumes that programs are encoded
in ASCII.
• In Ruby 1.8, you can specify a different encoding with the -K
command-line option.
• To run a Ruby program that includes Unicode characters encoded in
UTF-8, invoke the interpreter with the -Ku option.
• Ruby 1.9 also supports the -K option, but it is no longer the preferred
way to specify the encoding of a program file. Rather than have the
user of a script specify the encoding when they invoke Ruby, the
author of the script can specify the encoding of the script by placing a
special “coding comment” at the start of the file.* For example:
# coding: utf-8

BVRIT HYDERABAD College of Engineering for Women


• The comment must be written entirely in ASCII, and must include the
string coding followed by a colon or equals sign and the name of the
desired encoding (which cannot include spaces or punctuation other
than hyphen and underscore).
• Whitespace is allowed on either side of the colon or equals sign, and
the string coding may have any prefix, such as en to spell encoding.
• The entire comment, including coding and the encoding name, is
case-insensitive and can be written with upper- or lowercase letters.
• Encoding comments are usually written so that they also inform a text
editor of the file encoding. Emacs users might write:
# -*- coding: utf-8 -*-
• And vi users can write:
# vi: set fileencoding=utf-8 :

BVRIT HYDERABAD College of Engineering for Women


• An encoding comment like this one is usually only valid on the first
line of the file. It may appear on the second line, however, if the first
line is a shebang comment (which makes a script executable on
Unix-like operating systems):
#!/usr/bin/ruby -w
# coding: utf-8
• Encoding names are not case-sensitive and may be written in
uppercase, lowercase, or a mix. Ruby 1.9 supports at least the
following source encodings: ASCII-8BIT (also known as BINARY),
US-ASCII (7-bit ASCII), the European encodings ISO-8859-1 through
ISO-8859-15, the Unicode encoding UTF-8,

BVRIT HYDERABAD College of Engineering for Women


• As a special case, UTF-8-encoded files identify their encoding if the
first three bytes of the file are 0xEF 0xBB 0xBF. These bytes are
known as the BOM or “Byte Order Mark” and are optional in
UTF-8-encoded files. (Certain Windows programs add these bytes
when saving Unicode files.)
• In Ruby 1.9, the language keyword __ENCODING__ (there are two
underscores at the beginning and at the end) evaluates to the source
encoding of the currently executing code. The resulting value is an
Encoding object.

• UTF- UCS Transformation Format 8 -World Wide Web's most common character encoding.

BVRIT HYDERABAD College of Engineering for Women


Source Encoding and Default External Encoding

• In Ruby 1.9, it is important to understand the difference between the


source encoding of a Ruby file and the default external encoding of a
Ruby process.
• The source encoding is what we described earlier: it tells the Ruby
interpreter how to read characters in a script.
• Source encodings are typically set with coding comments.
• A Ruby program may consist of more than one file, and different files
may have different source encodings.
• The source encoding of a file affects the encoding of the string literals
in that file.

BVRIT HYDERABAD College of Engineering for Women


• The default external encoding is something different: this is the
encoding that Ruby uses by default when reading from files and
streams.
• The default external encoding is global to the Ruby process and does
not change from file to file.
• Normally, the default external encoding is set based on the locale that
your computer is configured to. But you can also explicitly specify the
default external encoding with command-line options, as we’ll
describe shortly.
• The default external encoding does not affect the encoding of string
literals, but it is quite important for I/O,

BVRIT HYDERABAD College of Engineering for Women


• In Ruby 1.9, the -K option exists for compatibility with Ruby 1.8 but is
not the preferred way to set the default external encoding.
• Two new options, -E and --encoding, allow you to specify an encoding
by its full name rather than by a one-character abbreviation.
• For example:
ruby -E utf-8 # Encoding name follows -E
ruby -Eutf-8 # The space is optional
ruby --encoding utf-8 # Encoding following --encoding with a space
ruby --encoding=utf-8 # Or use an equals sign with --encoding

BVRIT HYDERABAD College of Engineering for Women


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, for example.
• 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.

BVRIT HYDERABAD College of Engineering for Women


• Another difference between Ruby and compiled languages has to do
with module, class, and method definitions.
• In compiled languages, these are syntactic structures that are
processed by the compiler. In Ruby, they are statements like any
other.
• When the Ruby interpreter encounters a class definition, it executes
it, causing a new class to come into existence.
• Similarly, when the Ruby interpreter encounters a method definition,
it executes it, causing a new method to be defined. Later in the
program, the interpreter will probably encounter and execute a
method invocation expression for the method, and this invocation will
cause the statements in the method body to be executed.

BVRIT HYDERABAD College of Engineering for Women


• The Ruby interpreter is invoked from the command line and given a
script to execute.
• Very simple one-line scripts are sometimes written directly on the
command line.
• More commonly, the name of the file containing the script is
specified. The Ruby interpreter reads the file and executes the script.
It first executes any BEGIN blocks. Then it starts at the first line of the
file and continues until one of the following happens:
• It executes a statement that causes the Ruby program to terminate.
• It reaches the end of the file.
• It reads a line that marks the logical end of the file with the token __END__.

BVRIT HYDERABAD College of Engineering for Women


Package Management with RUBYGEMS
• 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.
*A Gemfile is a file that is created to describe the gem dependencies required to run a Ruby program.
*A Gemfile should always be placed in the root of the project directory.

BVRIT HYDERABAD College of Engineering for Women


• 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.

BVRIT HYDERABAD College of Engineering for Women


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.
• After downloading and unpacking the distribution, you can install it
using the included installation script.
% cd rubygems-0.7.0
% ruby install.rb
• Depending on your operating system, you may need suitable
privileges to write files into Ruby’s site_ruby/ and bin/ directories.
• The best way to test that RubyGems was installed successfully also
happens to be the most important command you’ll learn.

BVRIT HYDERABAD College of Engineering for Women


% gem help
• RubyGems is a sophisticated package manager for Ruby. This is a basic help
message containing pointers to more information.
• Usage:
gem -h/--help
gem -v/--version
gem command [arguments...] [options...]
• Examples:
gem install rake
gem list --local
gem build package.gemspec
gem help install

BVRIT HYDERABAD College of Engineering for Women


• Further help:
gem help commands list all 'gem' commands
gem help examples show some examples of usage
gem help <COMMAND> show help on COMMAND
(e.g. 'gem help install')
• Further information:
http://rubygems.rubyforge.org

BVRIT HYDERABAD College of Engineering for Women


Installing Application Gems
• Jim Weirich’s Rake (http://rake.rubyforge.org) holds the distinction of being the first
application that was available as a gem. It’s generally a great tool to have around, as it is a
build tool similar to Make and Ant.
• Locating and installing Rake with RubyGems is simple.
% gem install -r rake
Attempting remote installation of 'Rake’
Successfully installed rake, version 0.4.3
% rake --version
rake, version 0.4.3
• RubyGems downloads the Rake package and installs it. Because Rake is an application,
RubyGems downloads both the Rake libraries and the command-line program rake.

NOTE: Rake is a native tool for Ruby, similar to Unix's “make”. It is used to handle
administrative commands or tasks, which are stored either in a Rakefile or in a . rake file

BVRIT HYDERABAD College of Engineering for Women


• During installation, you can also add the -t option to the RubyGems
install command, causing RubyGems to run the gem’s test suite (if
one has been created).
• If the tests fail, the installer will prompt you to either keep or discard
the gem. This is a good way to gain a little more confidence that the
gem you’ve just downloaded works on your system the way the
author intended.
% gem install SomePoorlyTestedProgram -t
Attempting local installation of 'SomePoorlyTestedProgram-1.0.1’
Successfully installed SomePoorlyTestedProgram, version 1.0.1
23 tests, 22 assertions, 0 failures, 1 errors...keep Gem? [Y/n] n
Successfully uninstalled SomePoorlyTestedProgram version 1.0.1

BVRIT HYDERABAD College of Engineering for Women


Installing and Using Gem Libraries

• Using RubyGems to install a complete application was a good way to get


your feet wet and to start to learn your way around the gem command.

• However, in most cases, you’ll use RubyGems to install Ruby libraries for
use in your own programs.

• Since RubyGems enables you to install and manage multiple versions of the
same library, you’ll also need to do some new, RubyGems-specific things
when you require those libraries in your code

BVRIT HYDERABAD College of Engineering for Women


• You first need to find and install the BlueCloth gem.
% gem query -rn Blue
*** REMOTE GEMS ***
BlueCloth (0.0.4, 0.0.3, 0.0.2)
• BlueCloth is a Ruby implementation of Markdown, a Markdown
allows you to write using an text-to-HTML conversion tool for
web writers. Easy-to-read, easy-to-write plain text format, then
convert it to structurally valid XHTML (or HTML).

BVRIT HYDERABAD College of Engineering for Women


• This invocation of the query command uses the -n option to search the
central gem repository for any gem whose name matches the regular
expression /Blue/.
• The results show that three available versions of BlueCloth exist (0.0.4,
0.0.3, and 0.0.2).
• Because you want to install the most recent one, you don’t have to state an
explicit version on the install command; the latest is downloaded by
default.
% gem install -r BlueCloth
Attempting remote installation of 'BlueCloth’
Successfully installed BlueCloth, version 0.0.4

BVRIT HYDERABAD College of Engineering for Women


Generating API Documentation
• You need some API documentation to get started. Fortunately, with the
addition of the --rdoc option to the install command, RubyGems will
generate RDoc documentation for the gem it is installing.
% gem install -r BlueCloth --rdoc
Attempting remote installation of 'BlueCloth’
Successfully installed BlueCloth, version 0.0.4
Installing RDoc documentation for BlueCloth-0.0.4...
WARNING: Generating RDoc on .gem that may not have RDoc.
bluecloth.rb: cc..............................
Generating HTML...

BVRIT HYDERABAD College of Engineering for Women


Let’s Code!
• BlueCloth is installed and ready to write some code. Having used RubyGems to
download the library, we can now also use it to load the library components into
our application. Prior to RubyGems, we’d say something like
require 'bluecloth'
• With RubyGems, we can take advantage of its packaging and versioning support.
To do this, we use require_gem in place of require.
require 'rubygems’
require_gem 'BlueCloth', ">= 0.0.4"
doc = BlueCloth::new <<MARKUP
This is some sample [text][1]. Just learning to use [BlueCloth][1].
Just a simple test.
[1]: http://ruby-lang.org
MARKUP
puts doc.to_html

BVRIT HYDERABAD College of Engineering for Women


produces:
<p>This is some sample <a href="http://ruby-lang.org">text</a>. Just
learning to use <a href="http://ruby lang.org">BlueCloth</a>.
Just a simple test.</p>
• The first two lines are the RubyGems-specific code. The first line loads the
RubyGems core libraries that we’ll need in order to work with installed gems.
require 'rubygems’
• The second line is where most of the magic happens.
require_gem 'BlueCloth', '>= 0.0.4'
• This line adds the BlueCloth gem to Ruby’s $LOAD_PATH and uses require to
load any libraries that the gem’s creator specified to be autoloaded.

BVRIT HYDERABAD College of Engineering for Women


Creating Your Own Gems
Package Layout
• The first task in creating a gem is organizing your code into a directory
structure that makes sense. The same rules that you would use in creating a
typical tar or zip archive apply in package organization.
• Put all of your Ruby source files under a subdirectory called lib/. Later,
ensure that this directory will be added to Ruby’s $LOAD_PATH when users
load this gem.
• If it’s appropriate for your project, include a file under lib/yourproject.rb
that performs the necessary require commands to load the bulk of the
project’s functionality. Before RubyGems’ autorequire feature, this made
things easier for others to use a library.
• Even with RubyGems, it makes it easier for others to explore your code if
you give them an obvious starting point.

BVRIT HYDERABAD College of Engineering for Women


• Always include a README file including a project summary, pointers for
getting started.
• Use RDoc format for this file so you can add it to the documentation that
will be generated during gem installation.
• Remember to include a copyright and license in the README file, as many
commercial users won’t use a package unless the license terms are clear.
• Tests should go in a directory called test/. Many developers use a library’s
unit tests as a usage guide. It’s nice to put them somewhere predictable,
making them easy for others to find.
• Any executable scripts should go in a subdirectory called bin/.
• Source code for Ruby extensions should go in ext/.
• If you’ve got a great deal of documentation to include with your gem, it’s
good to keep it in its own subdirectory called docs/. If your README file is
in the top level of your package, be sure to refer readers to this location.
BVRIT HYDERABAD College of Engineering for Women
Gem Package Structure

Gem packages contain different sets of components. Each component gets placed inside
a dedicated location within the gem bundle.

All the below elements (and more) can go inside Gems:

● Application code;
● Tests;
● Description of dependencies;
● Binaries;
● Relevant Documentation;
● Information regarding the package (gemspec).

Gems are formed of a structure similar to the following:


Gem Package Structure

The main root directory of the Gem package.


/ [package_name] # 1
Location of the executable binaries if the package has
|__ /bin # 2 any.

|__ /lib # 3 Directory containing the main Ruby application code


(inc. modules).
|__ /test # 4 Location of test files
copyright and license in the README file
|__ README # 5
The Rake-file for libraries which use Rake for builds.

|__ Rakefile # 6 *.gemspec file, which has the name of the main
directory, contains all package meta-data, e.g. name,
version, directories etc.
|__ [name].gemspec # 7
Ruby and web: Writing CGI scripts
• Ruby is a general-purpose language; it can't properly be called a web
language at all. Even so, web applications and web tools in general are
among the most common uses of Ruby.

• Not only can you write your own SMTP server, FTP daemon, or Web
server in Ruby, but you can also use Ruby for more usual tasks such as
CGI programming or as a replacement for PHP.

Note: CGI is a standard method used to generate dynamic content on web pages. CGI
stands for Common Gateway Interface and provides an interface between the HTTP
server and programs generating web content.

BVRIT HYDERABAD College of Engineering for Women


Writing CGI Scripts:
• The most basic Ruby CGI script looks like this:
#!/usr/bin/ruby
puts "HTTP/1.0 200 OK"
puts "Content-type: text/html\n\n"
puts "<html><body>This is a test</body></html>"
• If you call this script test.cgi and uploaded it to a Unix-based Web hosting
provider with the right permissions, you could use it as a CGI script.

• The CGI standard was defined by the World Wide Web Consortium
(W3C) and specifies how a program interacts with a Hyper Text
Transfer Protocol

BVRIT HYDERABAD College of Engineering for Women


Using cgi.rb
• Class CGI provides support for writing CGI scripts. With it, you can
manipulate forms, cookies, and the environment; maintain stateful
sessions; and so on.
• When dealing with URLs and HTML code, you must be careful to
quote certain characters.
• For instance, a slash character ( / ) has special meaning in a URL, so
it must be “escaped” if it’s not part of the pathname. That is, any /
in the query portion of the URL will be translated to the string %2F
and must be translated back to a / for you to use it.
• Space and ampersand are also special characters. To handle this, CGI
provides the routines CGI.escape and CGI.unescape.

BVRIT HYDERABAD College of Engineering for Women


• Ruby comes with a special library called cgi that enables more
sophisticated interactions than those with the preceding CGI script.
#!/usr/bin/ruby

require 'cgi’
cgi = CGI.new

puts cgi.header
puts "<html><body>This is a test</body></html>"

BVRIT HYDERABAD College of Engineering for Women


require 'cgi’
puts CGI.escape("Nicholas Payton/Trumpet & Flugel Horn")
produces:
Nicholas+Payton%2FTrumpet+%2F+Flugel+Horn

• More frequently, you may want to escape HTML special characters.


require 'cgi’
puts CGI.escapeHTML("a < 100 && b > 200")
produces:
a &lt; 100 &amp;&amp; b &gt; 200

BVRIT HYDERABAD College of Engineering for Women


Form Processing
• Using class CGI gives you access to HTML query parameters in two
ways. Suppose we are given a URL of /cgi-bin/test.cgi?FirstName =
Zara&LastName = Ali.
• You can access the parameters FirstName and LastName using CGI#[]
directly as follows −
#!/usr/bin/ruby
require 'cgi’
cgi = CGI.new
cgi['FirstName'] # => ["Zara"]
cgi['LastName'] # => ["Ali"]

BVRIT HYDERABAD College of Engineering for Women


• If a form contains multiple fields with the same name, the corresponding
values will be returned to the script as an array. The [] accessor returns just
the first of these.index the result of the params method to get them all.
• In this example, assume the form has three fields called "name" and
entered three names "Zara", "Huma" and "Nuha" −
#!/usr/bin/ruby

require 'cgi’
cgi = CGI.new
cgi['name'] # => "Zara"
cgi.params['name’] # => ["Zara", "Huma", "Nuha"]
cgi.keys # => ["name"]
cgi.params # => {"name"=>["Zara", "Huma", "Nuha"]}

BVRIT HYDERABAD College of Engineering for Women


• Ruby will take care of GET and POST methods automatically. There is no separate treatment for
these two different methods.
• An associated, but basic, form that could send the correct data would have the HTML code like so

<html>
<body>
<form method = "POST" action = "http://www.example.com/test.cgi">
First Name :<input type = "text" name = "FirstName" value = "" />
<br />
Last Name :<input type = "text" name = "LastName" value = "" />
<input type = "submit" value = "Submit Data" />
</form>
</body>
</html>

BVRIT HYDERABAD College of Engineering for Women


• The GET Method is used to request data from a specified resource.
• Note that the query string (name/value pairs) is sent in the URL of a GET request

/test/demo_form.php?name1=value1&name2=value2

• GET requests can be cached


• GET requests remain in the browser history
• GET requests can be bookmarked

• POST requests are never cached


• POST requests do not remain in the browser history
• POST requests cannot be bookmarked

POST /test/demo_form.php HTTP/1.1


Host: w3schools.com
name1=value1&name2=value2
Creating Forms and HTML
#!/usr/bin/ruby
• CGI contains a huge
require "cgi"
number of methods used cgi = CGI.new("html4")
to create HTML. You will cgi.out {
find one method per tag. In cgi.html {
order to enable these cgi.head { "\n"+cgi.title{"This Is a Test"} } +
methods, you must create cgi.body { "\n"+
a CGI object by calling cgi.form {"\n"+
CGI.new. cgi.hr +
• To make tag nesting easier, cgi.h1 { "A Form: " } + "\n"+
these methods take their cgi.textarea("get_text") +"\n"+
content as code blocks. The cgi.br +
code blocks should return cgi.submit
a String, which will be used }
as the content for the tag. }
}
}

BVRIT HYDERABAD College of Engineering for Women


Cookies
• Cookies are a way of letting Web applications store their state on the
user’s machine.
• Cookies are still a convenient way of remembering session
information.
• The Ruby CGI class handles the loading and saving of cookies for you.
• Cookies can be accessed associated with the current request using the
CGI#cookies method, and can be 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.

BVRIT HYDERABAD College of Engineering for Women


#!/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 }

BVRIT HYDERABAD College of Engineering for Women


Sessions
• Cookies by themselves still need a bit of work to be useful.
• Session are required: information that persists between requests
from a particular Web browser.
• Sessions are handled by class CGI::Session, which uses cookies but
provides a higher-level abstraction.
• As with cookies, sessions emulate a hashlike behavior, associate
values with keys.
• Unlike cookies, sessions store the majority of their data on the server,
using the browser-resident cookie simply as a way of uniquely
identifying the server-side data.

BVRIT HYDERABAD College of Engineering for Women


• Sessions also give you a choice of storage techniques for this data: it
can be held in regular files, in a PStore in memory, or even in your
own customized store.
• Sessions should be closed after use, as this ensures that their data is
written out to the store.
• When permanently finished with a session, you should delete it.

BVRIT HYDERABAD College of Engineering for Women


Choice of Web Servers
• Ruby scripts run under the control of the Apache Web server.

• Ruby 1.8 and later comes bundled with WEBrick, a flexible, pure-Ruby
HTTP server toolkit.

• It’s an extensible plug in–based framework that lets you write servers
to handle HTTP requests and responses.

Note: WEBrick is a Ruby library providing simple HTTP web servers.

BVRIT HYDERABAD College of Engineering for Women


#!/usr/bin/ruby
require 'webrick’
include WEBrick
s = HTTPServer.new(
:Port => 2000,
:DocumentRoot => File.join(Dir.pwd, "/html")
)
trap("INT") { s.shutdown }
s.start
• The HTTPServer constructor creates a new Web server on port 2000. The
code sets the document root to be the html/ subdirectory of the current
directory. It then uses Kernel.trap to arrange to shut down tidily on
interrupts before starting the server running. If browser is pointed at
http://localhost:2000, a listing of html subdirectory will be visible.

BVRIT HYDERABAD College of Engineering for Women


SOAP and Web Services
• Speaking of SOAP, Ruby now comes with an implementation of SOAP.

• SOAP lets to write both servers and clients using Web services. By their nature,
these applications can operate both locally and remotely across a network.

• SOAP applications are also unaware of the implementation language of their


network peers, so SOAP is a convenient way of interconnecting Ruby applications
with those written in languages such as Java, Visual Basic, or C++.

Note:SOAP is the Simple Object Access Protocol, a messaging standard defined by


the World Wide Web Consortium and its member editors. SOAP uses an XML data
format to declare its request and response messages, relying on XML Schema

BVRIT HYDERABAD College of Engineering for Women


• SOAP is basically a marshalling mechanism which uses XML to send
data between two nodes in a network. It is typically used to
implement remote procedure calls, RPCs, between distributed
processes.
• A SOAP server publishes one or more interfaces. These interfaces
are defined in terms of data types and methods that use those
types.
• SOAP clients then create local proxies that SOAP connects to
interfaces on the server.
• A call to a method on the proxy is then passed to the corresponding
interface on the server.
• Return values generated by the method on the server are passed
back to the client via the proxy.

BVRIT HYDERABAD College of Engineering for Women


Ruby Tk
• The Ruby Application Archive contains several extensions that
provide Ruby with a graphical user interface (GUI), including
extensions for Fox, GTK, and others.
• The Tk extension is bundled in the main distribution and works on
both Unix and Windows systems.
• To use it, install TK on your system.
• Tk is a large system, so no time waste or resources by delving too
deeply into Tk itself but instead concentrate on how to access Tk
features from Rub

The standard graphical user interface (GUI) for Ruby is Tk.

BVRIT HYDERABAD College of Engineering for Women


• Tk works along a composition model—that is, start by creating a
container (such as a TkFrame or TkRoot) and then create the
widgets (another name for GUI components) that populate it, such
as buttons or labels.

• When ready to start the GUI, invoke Tk.mainloop.

• The Tk engine then takes control of the program, displaying


widgets and calling the code in response to GUI events.

BVRIT HYDERABAD College of Engineering for Women


Simple Tk Application
• A simple Tk application in Ruby may look something like this.
require 'tk’
root = TkRoot.new { title "Ex1" }
TkLabel.new(root) do
text 'Hello, World!’
pack('padx' => 15, 'pady' => 15, 'side' => 'left’)
end
Tk.mainloop
• After loading the TK extension module, create a root-level frame using
TkRoot.new.
• Then make a TkLabel widget as a child of the root frame, setting several
options for the label.
• Finally, pack the root frame and enter the main GUI event loop.

BVRIT HYDERABAD College of Engineering for Women


Widgets
• Creating widgets is easy.
• Take the name of the widget as given in the Tk documentation and add a Tk
to the front of it.
• For instance, the widgets Label, Button, and Entry become the classes
TkLabel, TkButton, and TkEntry.
• Create an instance of a widget using new, just as any other object.
• If a parent is not specified for a given widget, it will default to the
root-level frame.
• Specify the parent of a given widget, along with many other options—color,
size, and so on.
• It is required to be able to get information back from our widgets while our
program is running by setting up callbacks (routines invoked when certain
events happen) and sharing data.

BVRIT HYDERABAD College of Engineering for Women


Setting Widget Options
• Options for widgets are usually listed with a hyphen—as a
command-line option would be.
• In Perl/Tk, options are passed to a widget in a Hash.
• It can be done in Ruby as well, but can also pass options using a code
block; the name of the option is used as a method name within the
block and arguments to the option appear as arguments to the
method call.
• Widgets take a parent as the first argument, followed by an optional
hash of options or the code block of options.

BVRIT HYDERABAD College of Engineering for Women


TkLabel.new(parent_widget) do
text 'Hello, World!’
pack('padx' => 5,
'pady' => 5,
'side' => 'left’)
end
# or
TkLabel.new(parent_widget, 'text' => 'Hello, World!').pack(...)

BVRIT HYDERABAD College of Engineering for Women


• One small caution when using the code block form: the scope of
variables is not what you think it is.
• The block is actually evaluated in the context of the widget’s object,
not the caller’s. This means that the caller’s instance variables will not
be available in the block, but local variables from the enclosing scope
and global will be.
• Distances (as in the padx and pady options in the examples) are
assumed to be in pixels but may be specified in different units using
one of the suffixes c (centimeter), I (inch), m (millimeter), or p (point).
"12p", for example, is twelve points.

BVRIT HYDERABAD College of Engineering for Women


Getting Widget Data
• Information can be get back from widgets by using callbacks and by binding
variables.
• Callbacks are very easy to set up.
• The command option (shown in the TkButton call) takes a Proc object, which will
be called when the callback fires.
• Pass the proc in as a block associated with the method call, but could also have
used Kernel.lambda to generate an explicit Proc object.
require 'tk’
TkButton.new do
text "EXIT"
command { exit }
pack('side'=>'left', 'padx'=>10, 'pady'=>10)
end
Tk.mainloop

BVRIT HYDERABAD College of Engineering for Women


• A Ruby variable can be bind to a Tk widget’s value using a
TkVariable proxy.
• This arranges things so that whenever the widget’s value changes,
the Ruby variable will automatically be updated, and whenever the
variable is changed, the widget will reflect the new value.
• Notice how the TkCheckButton is set up; the documentation says
that the variable option takes a var reference as an argument.
• Create a Tk variable reference using TkVariable.new.
• Accessing mycheck.value will return the string “0” or “1” depending
on whether the checkbox is checked.
• Use the same mechanism for anything that supports a var
reference, such as radio buttons and text fields.

BVRIT HYDERABAD College of Engineering for Women


require 'tk'
packing = { 'padx'=>5, 'pady'=>5, 'side' => 'left' }
checked = TkVariable.new
def checked.status
value == "1" ? "Yes" : "No"
TkCheckButton.new do
end
variable checked
status = TkLabel.new do pack(packing)
text checked.status end
pack(packing) TkButton.new do
text "Show status"
end
command { status.text(checked.status) }
pack(packing)
end
Tk.mainloop

BVRIT HYDERABAD College of Engineering for Women


Binding Events
• Our widgets are exposed to the real world; they get clicked, the
mouse moves over them, the user tabs into them; all these things,
and more, generate events that we can capture.
• A binding can be created from an event on a particular widget to a
block of code, using the widget’s bind method.
• For instance, a button widget is created that displays an image.
• We’d like the image to change when the user’s mouse is over the
button.

BVRIT HYDERABAD College of Engineering for Women


require 'tk'
image1 = TkPhotoImage.new { file "img1.gif" }
image2 = TkPhotoImage.new { file "img2.gif" }
b = TkButton.new(@root) do
image image1
command { exit }
pack
end
b.bind("Enter") { b.configure('image'=>image2) }
b.bind("Leave") { b.configure('image'=>image1) }
Tk.mainloop

BVRIT HYDERABAD College of Engineering for Women


• First, create two GIF image objects from files on disk, using
TkPhotoImage.
• Next create a button (very cleverly named “b”), which displays the
image image1.
• Then bind the Enter event so that it dynamically changes the image
displayed by the button to image2 when the mouse is over the
button, and the Leave event to revert back to image1 when the
mouse leaves the button.

BVRIT HYDERABAD College of Engineering for Women


• The example shows the simple events Enter and Leave. But the named
event given as an argument to bind can be composed of several substrings,
separated with dashes, in the order modifier-modifier-type-detail.
• Modifiers are listed in the Tk reference and include Button1, Control, Alt,
Shift, and so on.
• Type is the name of the event (taken from the X11 naming conventions)
and includes events such as ButtonPress, KeyPress, and Expose.
• Detail is either a number from 1 to 5 for buttons or a keysym for keyboard
input.
• For instance, a binding that will trigger on mouse release of button 1 while
the control key is pressed could be specified as
ControlButton1ButtonRelease
or
ControlButtonRelease1

BVRIT HYDERABAD College of Engineering for Women


Canvas
• Tk provides a Canvas widget with which
you can draw and produce PostScript
output.
• Clicking and holding button 1 will start a
line, which will be “rubber-banded” as
you move the mouse around. When
you release button 1, the line will be
drawn in that position.
• A few mouse clicks, and get an instant
masterpiece.

BVRIT HYDERABAD College of Engineering for Women


Scrolling
• Unless you plan on drawing very small pictures, the previous example
may not be all that useful. TkCanvas, TkListbox, and TkText can be set
up to use scrollbars, so you can work on a smaller subset of the “big
picture.”
• Communication between a scrollbar and a widget is bidirectional.
• Moving the scrollbar means that the widget’s view has to change; but
when the widget’s view is changed by some other means, the
scrollbar has to change as well to reflect the new position.
• In the code fragment, start by creating a plain old TkListbox and an
associated TkScrollbar.

BVRIT HYDERABAD College of Engineering for Women


• The scrollbar’s callback (set with command) will call the list widget’s y
view method, which will change the value of the visible portion of the
list in the y direction.

• After that callback is set up, make the inverse association: when the
list feels the need to scroll, set the appropriate range in the scrollbar
using TkScrollbar#set.

BVRIT HYDERABAD College of Engineering for Women


THANK YOU
LAB CYCLE -1

1. Write a Ruby script to create a new


string which is n copies of a given string
where n is a nonnegative integer
2. Write a Ruby script which accept the
radius of a circle from the user and
compute the parameter and area.
3. Write a Ruby script which accept the
user's first and last name and print them
in reverse order with a space between
them
4. Write a Ruby script to accept a filename
from the user print the extension of
that.
5. Write a Ruby script to find the greatest
of three numbers

You might also like