S.L Unit-I
S.L Unit-I
Introduction
Ruby, Rail , The structure and Execution of Ruby Programs, Package Management with
RUBYGEMS, Ruby and web: Writing scripts, cookies Choice web services, SOAP and
webservices,
Ruby Tk - Simple Tk Application, widgets Binding events, Caracolling
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 favourite vi editor
to write Ruby programs.
RubyWin is a Ruby Integrated Development Environment (IDE) for Windows.
Ruby Development Environment (RDE) is also a very good IDE for windows users.
Interactive Ruby (IRb)
Interactive Ruby (IRb) provides a shell for experimentation. Within the IRb shell, you
can immediately view expression results, line by line.
This tool comes along with Ruby installation so you have nothing to do extra to have
IRb working.
Just type irb at your command prompt and an Interactive Ruby Session will start as
given below
$irb
irb 0.6.1(99/09/16)
irb(main):001:0> def hello
irb(main):002:1> out "Hello World"
irb(main):003:1> puts out
irb(main):004:1> end
nil
irb(main):005:0> hello
Hello World
nil
irb(main):006:0>
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.
BEGIN And When
Do End Case
Next Or For
Then Unless Retry
END Begin While
Else Ensure Class
Nil reDO If
True Until Return
Alias Break Definse
Elsif False If_FILE_
Not Rescue Defined
Undef _LINE_ ?
Ensure Super Module
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
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
1. 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
o 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
o 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.
o Ruby programming language do not support all these.
4. Object Orientation
o 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.
o 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.
o The developer of Perl believes that choosing of OO should be the programmer's
decision; language should not force a programmer to switch to 00.
#class variables
@@type_of_animal = 4
@@no_of_animal = 3
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
# class name is box
class Box
# class variable
@@No_of_color = 3
end
# Two Objects of Box class
sbox Box.new
nbox Box.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
Syntax:
def method_name
#statements or code to be executed
end
#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! -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"
}
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
#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")
Output:
Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya
Customer id 2 Customer name Poul Customer address New Empire road, Khandala
#Call Methods
Cust1.display_details ()
Cust2.display_details ()
Cust1.display details () cust2.display details ()
Class Variables: A class variable name always starts with @@ sign.lt 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.
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
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
Punctuation
• 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
sort! # A method invoked by assignment 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:
LINE case ensure not then
_ENCODING class false or true
_FILE_ def for redo undef
BEGIN defined? If rescue unless
END do in retry untile
Alias else module return when
And elsif next self while
Begin end nil super yield
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
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"
o AGE = 23
o 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
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
10 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
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.
Ex:
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
Ex:
Si=0
$num=5
while $i <$num do
puts("Inside the loop i = #$i" )
$i +=1
End
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
• 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
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.
STRUCTURE OF A GEM
o 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.
o 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.
o RubyGems will automatically download the correct version for your platform.
See gem help platform for full details.
o Inside gems are the following components:
o Code (including tests and supporting utilities)
o Documentation
gemspec
THE GEMSPEC
The gemspec specifies the information about a gem such as its name, version, description,
authors and homepage.
Gem::Specification.new do |s|
s.name = 'example'
s.version = '0.1.0'
s.licenses = ['MIT']
s.summary = "This is an example!"
s.description = "Much longer explanation of the example!"
s.authors = ["Ruby Coder"]
s.email = 'rubycoder@example.com'
s.files = ["lib/example.rb"]
s.homepage = 'https://rubygems.org/gems/example'
s.metadata = { "source_code_uri" =>
"https://github.com/example/example" }
end
$ tree
.
├── Rakefile
├── bin
│ └── hola
├── hola.gemspec
├── lib
│ ├── hola
│ │ └── translator.rb
│ └── hola.rb
└── test
└── test_hola.rb
CGI Chart
WEB SERVER
WEB CLIENT
SERVER SIDE SCRIPT
DATABASE
HTTP Protocol
• 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:
o 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.
o 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.
o 2. Do what you want with the data
1 Write the HTML response to STDOUT.
⚫ he following code will let you know how you can escape HTML special characters?
• puts CGI.escapeHTML( '<a href="/san">Go to the site (Includehelp.com)</a>')
• Output
<a href="/san">Go to the site(Includehelp.com)</a>
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,require "cgi
Require “cgi”
cgi = CGI.new("html5")
cgi.out {
cgi.html {
cgi.head { "\n"+cgi.title("It is an Example of forn" }} +
cgi.body { "\n" cgi.fora ("\n"+
cgi.from { "\n"+
cgi.hr +
cgi.hr1 { “A Form: “ } + "\n"+
cgi.hr2 { “A Basic form: “ } + "\n"+
cgi.text area("get_text") +"\n" +
cgi.button("click_here")+ " cgi.hr1 { “A Form: “ } + "\n"+
cgi.hr +
cgi.br +
cgi-submit
}
}
}
}
output
Content-Type: text/html
Content-Length: 317
<!DOCTYPE HTML><HTML><HEAD>
<TITLE>It is an Example of form</TITLE> </HEAD> <BODY>
<FORM METHOD="post" ENCTYPE="application/x-www-form-urlencoded">
<HR><H1>A Form: </H1>
<H2>A Basic Form:</H2>
<TEXTAREA NAME="get text" COLS="70" ROWS="10"></TEXTAREA>
<BUTTON></BUTTON>
<HR><BR><INPUT TYPE="submit"></FORM></BODY></HTML>
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 youcan set cookies back into the browser by setting the cookies parameter
of CGI#out treference either a single cookie or an array of cookies
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 eabl
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 Active
Tcl.
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'
root = TkRoot.new { title "Hello, World!" }
TkLabel.new(root) do
text 'Hello, World!'
pack { padx 15; pady 15; side 'left' }
end
Tk.mainloop
• Syntax
• Syntax
⚫ 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
Ib1TkLabel.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
• A Canvas widget implements structured graphics. A canvas displays any number of items,
which may be things like rectangles, circles, lines, and text.
• Syntax
TkCanvas.new {
.....Standard Options.....
.....Widget-specific Options....
}
......Widget-specific Options....
}
Creating Item
When you create a new canvas widget, it will essentially be a large rectangle with
nothing on it; truly a blank canvas in other words. To do anything useful with it, you'll
need to add items to it.
there are a wide variety of different types of items you can add
Arc Items
Bitmap Items
Image Items
Line Items
Rectangle Item
• 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.
Star> 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.
Tag =>staglist-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 Tkclmage.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
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', '2', '3c', '3c', 'outline' => 'black', 'fill' => 'blue')
• canvas.pack
• 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
• require "tk"
• canvas = TkCanvas.new
• TkcRectangle.new(canvas, '1c', '2c', '3c', '3c', 'outline' => 'black', 'fill' => 'blue')
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.
• S method is used to query and change the vertical position of the text in the widget's window.