0% found this document useful (0 votes)
2 views

S.L UNIT-I

The document provides an overview of Ruby, a pure object-oriented programming language created in 1993, highlighting its features, advantages, and applications in web development. It contrasts Ruby with other programming languages and frameworks, such as Java and Ruby on Rails, and discusses the differences between compiled and interpreted languages. Additionally, it covers scripting languages, server-side and client-side scripting, and includes practical information on Ruby syntax and usage.

Uploaded by

tevibupe
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)
2 views

S.L UNIT-I

The document provides an overview of Ruby, a pure object-oriented programming language created in 1993, highlighting its features, advantages, and applications in web development. It contrasts Ruby with other programming languages and frameworks, such as Java and Ruby on Rails, and discusses the differences between compiled and interpreted languages. Additionally, it covers scripting languages, server-side and client-side scripting, and includes practical information on Ruby syntax and usage.

Uploaded by

tevibupe
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/ 41

1

RUBY 20.12.2024

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

Introduction to Scripting Languages


• All scripting languages are programming languages.
• Programming Languages: c, c ++, java
• The scripting language is basically a language where instructions are written for a run
time environment. They do not require the compilation step and are rather interpreted.
• A scripting language is a programming language designed for integrating and
communicating with other programming languages.
Advantages of scripting languages:
 Easy learning: The user can learn to code in scripting languages quickly, not much
knowledge of web technology is required.
 Fast editing: It is highly efficient with the limited number of data structures and
variables to use.
 Interactivity: It helps in adding visualization interfaces and combinations in web
pages. Modern web pages demand the use of scripting languages. To create enhanced
web pages, fascinated visual description which includes background and foreground
colors and so on.
 Functionality: There are different libraries which are part of different scripting
languages. They help in creating new applications in web browsers and are different
from normal programming languages.
Application of Scripting Languages:
 Scripting languages are used in many areas:
 Scripting languages are used in web applications. It is used in server side as well as
client side.
 Server side scripting languages are: JavaScript, PHP, Perl etc.
 Client side scripting languages are: JavaScript, AJAX, jQuery etc.
 Scripting languages are used in system administration.
For example: Shell, Perl, Python scripts etc.
 It is used in Games application and Multimedia.
 It is used to create plugins and extensions for existing applications.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


2
RUBY 20.12.2024

Compiler vs Interpreter
 A compiler takes entire program and converts it into object code which is typically
stored in a file. The object code is also referred as binary code and can be directly
executed by the machine after linking. Examples of compiled programming languages
are C and C++.
 An Interpreter directly executes instructions written in a a pro programming or scripting
language without previously converting them to an object code or machine code.
Examples of interpreted languages are Perl, Python and Matlab.
Following are some interesting facts about interpreters and compilers.
1. Both compilers and interpreters convert source code (text files) into tokens, both may
generate a parse tree, and both may generate immediate instructions. The basic
difference is that a compiler system, including a (built in or separate) linker, generates
a stand alone machine code program, while an interpreter system instead performs the
actions described by the high level program.
2. Once a program is compiled, its source code is not useful for running the code. For
interpreted programs, the source code is needed to run the program every time.
3. In general, interpreted programs run slower than the compiled programs.
4. Java programs are first compiled to an intermediate form, then interpreted by the
interpreter.
Server-side Scripting
 It helps work with the back end.
 It doesn't depend on the client.
 It helps provide a response to every request that comes in from the user/client.
 It runs on the web server.
 It requires the interaction with the server for the data to be process.
 Server side scripting languages such as PHP,ASP.net, ColdFusion, Python, Ruby on
Rails.
 It is considered to be a secure way of working with applications.
 It can be used to customize web pages.
 It can also be used to provide dynamic websites.
Client-side Scripting
 It helps work with the front end.
 It is visible to the users.
 The scripts are run on the client browser.
 It runs on the user/client's computer.
 It depends on the browser's version
 It doesn't interact with the server to process data.
 Client side scripting involves languages such as HTML, CSS, JavaScript.
 It helps reduce the load on the server.
 It is considered to be less secure in comparison to client side scripting.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


3
RUBY 20.12.2024

INTRODUCTION TO RUBY
Ruby is a pure object-oriented programming language. It was created in 1993 Japan by
Yukihiro Matsumoto, also known as Matz.
Ruby is "A Programmer's Best Friend".
 Ruby has features that are similar to those of Smalltalk, Perl, and Python. Perl, Python,
and Smalltalk are scripting languages.
 Smalltalk is a true object-oriented language.
Ruby, like Smalltalk, is a perfect object-oriented language.
 Using Ruby syntax is much easier than using Smalltalk syntax.
Features of Ruby
 Ruby is an open-source and is freely available on the Webe
 Ruby is a general-purpose, interpreted programming language.
 Ruby is a true object-oriented programming language.
 Ruby is a server-side scripting language similar to Python and PERL Ruby can be used
to write Common Gateway Interface (CGI) scripts.
 Ruby can be embedded into Hypertext Markup Language (HTML).
 Ruby has a clean and easy syntax that allows a new developer to learn very quickly and
easily.
 Ruby has similar syntax to that of many programming languages such as C++ and Perl.
 Ruby is very much scalable and big programs written in Ruby are easily maintainable.
 Ruby can be used for developing Internet and intranet applications.
 Ruby can be installed in Windows and Linux environments. Ruby support many GUI
tools such as Tcl.
 Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase.
 Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts.
 Ruby is being used in wide range of fields, especially in Web Applications and data
science.
 Ruby is a dynamic programming language therefore, it does not have hard rules on how
to build features and it is very close to spoken languages.
 Ruby is being used in wide range of fields, especially in Web Applications and data
science.
 Ruby is a dynamic programming language therefore, it does not have hard rules on how
to build features and it is very close to spoken languages.
 One of the goals of Ruby is to allow the simple and fast creation of Web applications.
Because of this there is much less tedious workthan many other programming
languages. Ruby provides small, elegant and powerful code.
 Ruby is an open source language. It is free to copy, use, modify and distribute. Since
Ruby is available to be used in other projects, programmers can make necessary
changes and can code without feeling restricted.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


4
RUBY 20.12.2024

 Programmers are allowed to maintain reference counts in extension libraries with the
help of mark-and-sweep garbage collection, which is one of the features of Ruby. It can
also dynamically load extension libraries.
Difference between Ruby and Ruby on Rails:
 Ruby is a programming language whereas Ruby on Rails is a Web framework.
 Ruby is an Object Oriented, dynamic, interpreted scripting language whereas Ruby on
Rails is an Open source Web application framework, which runs on the Ruby
programming language.
Ruby on Rails:
 Ruby on Rails (RoR) is an open source Web application frameworks.
 Ruby on Rails is one of the main features of Ruby.
 The programming language, Ruby is used to write Ruby on Rails.
 Ruby on Rails, simply called Rails was designed for Ruby by David Heinemeier
Hansson.
 It was released in July 2004.
Ruby versus Java:
 Ruby based program runs directly as it is an interpreted scripting language whereas
Java- based codes are first compiled then executed.
 Ruby does not have any data types as Java. In Ruby the constructor name is always
"initialize" whereas in case of Java the constructor name is the name of the class.
 Ruby uses dynamic typing whereas Java uses static typing.
static typing vs dynamic typing
 Dynamically- typed languages perform type checking at runtime, while statically
typed languages perform type checking at compile time.... If a script written in a
statically-typed language (such as Java) contains errors, it will fail to compile until the
errors have been fixed.
Popular Ruby Editors
To write your Ruby programs, you will need an editor –

 If you are working on Windows machine, then you can use any simple text editor
like Notepad or Edit plus.
 VIM (Vi IMproved) is a very simple text editor. This is available on almost all Unix
machines and now Windows as well. Otherwise, your can use your 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.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


5
RUBY 20.12.2024

 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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


6
RUBY 20.12.2024

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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


7
RUBY 20.12.2024


 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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


8
RUBY 20.12.2024

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.

o Ruby also doesn't force you to choose an objective easier to


o Ruby also doesn't force you to choose an objective orientation, but if you do, it will be
much easier to use than in Perl.
5. Supporting of Regular Expression

 When we start a discussion on supporting of a regular expression, Perl has a


very good number of libraries than Ruby has. The Perl library of code CPAN is
incomparable with any other library.
 So the supporting capacity of regular expression of Perl is little more than Ruby.
But you need not worry as a user of Ruby, as it supports most of the regular
expressions.
8. Variable Type
• Perl has multiple variable types like a scalar, array, hash, etc. in contrast, Ruby programming
language offers only one variable type: reference to the object, the object can act like an array,
hash, or whatever, depends on demand.
9. Use of Sigils
o Perl uses the sigils like @, $, and % to denote variable types. Ruby uses sigils
such as @, @@, and $ to denote scope. To use all the variables in Perl except
function, the user has to put some sigils.
o But in the case of Ruby, there is no need for variables to work with local scopes.
10. File Extension
o A file extension is another major difference between Perl and Ruby. Perl
programs have the .pl file extension while Ruby programs have the .rb file
extension.
11. Influenced Language

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


9
RUBY 20.12.2024

o Perl is influenced by C, Basic, Lisp, Ada, etc. It mainly resembles with C


language. On the other hand, Ruby is influenced by C, Perl, Smalltalk, Ada,
Lisp, etc. Ruby has some additional touch from Smalltalk which is missing in
Perl.
• Conclusion
 Perl is a quite old language, started its journey eight years ago than Ruby does. So, in
the cases of community backup, availability of libraries for any need, documentation,
Perl is far ahead of Ruby. Ruby has its merits in providing object- oriented features that
help in keeping large code bodies maintainable.
 So, both have some sort of merits and demerits. So, in the competition of Ruby vs Perl,
the choice of language depends completely on the programmer.
Ruby | Class & Object
 In object-oriented programming classes and objects plays an important role.
 A class is a blueprint from which objects are created. The object is also called as an
instance of a class.
 For Example, the animal is a class and mammals, birds, fish, reptiles, and amphibians
are the instances of the class. Similarly, the sales department is the class and the objects
of the class are sales data, sales manager, and secretary.
Defining a class in Ruby:
 In Ruby, one can easily create classes and objects. Simply write class keyword followed
by the name of the class. The first letter of the class name should be in capital letter.
Syntax:
class Class _name
end
E.g: class Customer
end E.g: class Customer
end
Example:
#class name is Animal
class Animal

#class variables
@@type_of_animal = 4
@@no_of_animal = 3
end

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


10
RUBY 20.12.2024

• 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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


11
RUBY 20.12.2024

#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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


12
RUBY 20.12.2024

Output:
Welcome to GeeksforGeeks!
Ruby BEGIN Statement
Syntax
BEGIN {
code
code2
}
 Declares code to be called before the program is run.
Example
puts "This is main Ruby Program"
BEGIN
{
puts "Initializing Ruby Program"
}

 This will produce the following result -


Initializing Ruby Program
This is main Ruby Program
Ruby END Statement
Syntax
END {
code
}
#!/usr/bin/ruby
puts "This is main Ruby Program"
END
{
puts "Terminating Ruby Program"
}
BEGIN
{

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


13
RUBY 20.12.2024

puts "Initializing Ruby Program"


}

 This will produce the following result -


 Initializing Ruby Program
 This is main Ruby Program Terminating Ruby Program Ruby Comments
Ruby | Types of Variables
There are different types of variables in Ruby:

 Local variables
 Instance variables
 Class variables
 Global variables
Each variable in Ruby is declared by using a special character at the start of the variable name
which is mentioned in the following table:
• Symbol Type of Variable
• [a-z] or_ Local Variable
•@ Instance Variable
• @@ Class Variable
$ Global Variable
• Local Variables: A local variable name always starts with a lowercase letter(a-z) or
underscore (_). These variables are local to the code construct in which they are declared. A
local variable is only accessible within the block of its initialization. Local variables are not
available outside the method. There is no need to initialize the local variables.
Example:

⚫ age = 10
• _Age = 20

• Instance Variables: An instance variable name always starts with a @ sign. They are similar
to Class variables but their values are local to specific instances of an object. Instance variables
are available across methods for any specified instance or object i.e. instance variables can
change from object to object. There is no need to initialize the instance variables and
uninitialized instance variable always contains a nil value.
class Customer

def initialize(id, name, addr)


#Instance Variables.
@cust_id=id

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


14
RUBY 20.12.2024

@cust name name


@cust addr addr
End

#displaying result
def display details() puts "Customer id #@cust_id"
puts "Customer name #@cust name"
puts "Customer address @cust addr"
end
end

#Create Objects
cust1 Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 Customer.new("2", "Poul", "New Empire road, Khandala")
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.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


15
RUBY 20.12.2024

⚫ 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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


16
RUBY 20.12.2024

comments.rb
author Jan Bodnar
=end
# prints message to the terminal puts "Comments example"
Embedded documents

• Ruby supports another style of multiline comment known as an embedded document.


These start on a line that begins begin and continue until (and include) a line that begins =end.
Any text that appears after begin or end is part of the comment and is also ignored, but that
extra text must be separated from the =begin and end by at least one space.
=begin Someone needs to fix the broken code below!
Any code here is commented out
=end
Ruby white space
White space in Ruby is used to separate tokens and terminate statements in the source file. It
is also used to improve readability of the source code.
if true then
puts "A message"
end
White spaces are required in some places. For example between the if keyword and the true
keyword. Or between the puts method and the actual string. In other places, it is forbidden. It
cannot be present in variable identifiers or language keywords.
 a=1
 b=2
 c=3
The amount of space put between tokens is irrelevant for the Ruby interpreter. However, it is
important to have one style throughout the project.
x=5+3
puts x
y=5+3
puts y
z=5+3
puts z

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


17
RUBY 20.12.2024

O/P:
8
5
8
Punctuation

• Ruby uses punctuation characters for a number of purposes.

• Most Ruby operators are written using punctuation characters, such as + for addition, * for
multiplication, and || for the Boolean OR operation.
2.4 Identifiers
 An identifier is simply a name. Ruby uses identifiers to name variables, methods,
classes, and so forth.
 Ruby identifiers consist of letters, numbers, and underscore characters, but they may
not begin with a number.
 Identifiers may not include whitespace and they may not include punctuation characters
except as described here
 A variable is an identifier, which holds a value. In programming we say that we assign
a value to a variable. Technically speaking, a variable is a reference to a computer
memory, where the value is stored. In Ruby, a variable can hold a string, a number or
various objects. Variables can be assigned different values over time.
 Identifiers that begin with a capital letter A-Z are constants, and the Ruby interpreter
will issue a warning (but not an error) if you alter the value of such an identifier.
 Class and module names must begin with initial capital letters.
 The following are identifiers:
i
x2
old value
 _internal # Identifiers may begin with underscores
 PI # Constant
 By convention, multiword identifiers that are not constants are written with underscores
 like this, whereas multiword constants are written LikeThis or LIKE THIS
 Value
 value2
 company_name
These are valid variable names.

 12Val
 exx$
 first-name
These are examples of invalid variable names.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


18
RUBY 20.12.2024

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]

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


19
RUBY 20.12.2024

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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


20
RUBY 20.12.2024

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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


21
RUBY 20.12.2024

 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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


22
RUBY 20.12.2024

• 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

• This will produce the following result -


Inside the loop i=0
Inside the loop i=1
Inside the loop i=2
Inside the loop i=3
Inside the loop i=4
• Ruby for Statement
Syntax
for variable [, variable...] in expression [do]
code
end
Ex:
for i in 0..5
puts "Value of local variable is #{i}"
End
Output
Value of local variable is 0
Value of local variable is 1

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


23
RUBY 20.12.2024

Value of local variable is 2


Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
For (i=0;i<=5;i++)

Ruby Gems
 RubyGems is a package utility for Ruby, which installs Ruby software packages and
keeps them up-to-date.
 Check to see whether RubyGems is installed -
 $ gem --version
 0.9.0
 How do RubyGems work?

• The RubyGems software allows you to easily download, install, and use ruby software
packages on your system .... Gems can be used to extend or modify functionality in

Ruby Package Management with gem


• Ruby's package management system is known as RubyGems, and packages or
modules distributed using RubyGems are called "gems."
RubyGems makes it easy to install Ruby software and can automatically manage
complex dependencies between packages.
RubyGems is a standardized packaging and installation framework for libraries and
applications, making it easy to locate, install, upgrade, and uninstall Ruby packages
It provides users and developers with four main facilities.
• 1. A standardized package format,
2. A central repository for hosting packages in this format,
3. Installation and management of multiple, simultaneously installed versions of the
same library,
• 4. End-user tools for querying, installing, uninstalling, and otherwise manipulating
these packages.
• Before RubyGems came along, installing a new library involved searching the Web,
downloading a package, and attempting to install it-only to find that its dependencies
haven't been met.
If the library you want is packaged using RubyGems, however, you can now simply
ask RubyGems to install it (and all its dependencies). Everything is done for you.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


24
RUBY 20.12.2024

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

$ gem search ^rails


*** REMOTE***
rails 17.0.3)
rails-3-settinge 10.1.1) rallaam (0.1.0)
rails-action-args (0.1.1)
rails-action-authorisation (1.1.2)
[…….]

• If you see a gem you want more information on you can add the details option.
$gem search rails -d
REMOTE GEMS***
Rails (7.0.3)
Author: David Meinemeier Hansson
Homepage: https://rubyonrails.org
Full-stack web application framework.
INSTALLING GEMS
 The install command downloads and installs the gem and any necessary dependencies
then builds documentation for the installed gems.

$ gem install drip


Fetching drip-0.1.1.gem
Fetching shtres-0.4.5.gem
Building native extensions. This could while...

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


25
RUBY 20.12.2024

Successfully installed zbtree-0.4.5


Successfully installed drip-0.1.1 Parsing documentation for zbtree-0.4.5
Installing ri documentation for rbtree-0.4.5
Parsing documentation for drip-0.1.1
Installing ri documentation for drip-0.1.1
Done installing documentation for rbtree, drip 0 seconds
2 gems installed
LISTING INSTALLED GEMS
 The list command shows your locally installed gems:gem has other useful
subcommands as well. Some examples:
 gem list # List installed gems
 gem enviroment # Display RubyGems
configuration information
 gem update rails # Update a named gem
 gem update # Update all installed gems
 gem update-system #Update RubyGems itself
 gem uninstall rails # Remove an installed gem
UNINSTALLING GEMS
 The uninstall command removes the gems you have installed.

$ gem uninstall drip


Successfully uninstalled drip-0.1.1

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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


26
RUBY 20.12.2024

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 = '[email protected]'
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

o The lib directory contains the code for the gem


o The test or spec directory contains tests, depending on which test framework the
developer uses
o A gem usually has a Rake file, which the rake program uses to automate tests, generate
code, and perform other tasks.
o This gem also includes an executable file in the bin directory, which will be loaded
into the user's PATH when the gem is installed. Documentation is usually included in
the README and Online with the code.
o .When you install a gem, documentation is generated automatically for you. Most gems
include RDoc documentation.
In this chapter, we'll see how to
• 1. Install RubyGems on your computer.
• 2. Use RubyGems to install other applications and libraries.
• 3. Write your own gems.
Installing RubyGems

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


27
RUBY 20.12.2024

• To use RubyGems, you'll first need to download and install the RubyGems system
from the project's home page at http://rubygems.rubyforge.org
• % cd rubygems0.7.0
• % ruby install.rb
• The best way to test that RubyGems was installed successfully also happens to be the
learn
• % gem help
Installing Application Gems
• Let's start by using RubyGems to install an application that is written in Ruby. Jim
Weirich's Rake (http://rake.rubyforge.org) holds the distinction of being the first
application that was available as a gem.
• % gem install -r rake
• % rake --version
• # gem install rails
Successfully installed activesupport-1.4.4
Successfully installed activerecord-1.15.5
Successfully installed actionpack-1.13.5
Successfully installed actionmailer-1.3.5
Successfully installed actionwebservice-1.2.5
Successfully installed rails-1.2.5
6 gems installed
 As you can see, the gem install command installs the most recent version of the gem
you request and also installs any gems that the requested gem requires

Common Gateway Interface (CGI)?


 Ruby is a universal language, not just the one used in WEB development language, but
Ruby development in WEB applications and WEB tools are the most common.
 Not only you can use Ruby to write your own SMTP server, FTP program, or Ruby
Web server, but also can be use Ruby CGI programming.
 Let's take a moment to learn the Ruby CGI edited.
Web browsing
 To better understand how CGI works, we can click on a link on a web page or URL of
the process:
 1, use your browser to access the URL and connect to the HTTP web server.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


28
RUBY 20.12.2024

 2, Web server receives the request message will be parsed URL and look accessed files
on the server if there is to return the contents of the file, otherwise it returns an error
message.
 3, the browser …messages.
 CGI programs can be a Ruby script, Python script, PERL script, SHELL script, C or C
++ programs.

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.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


29
RUBY 20.12.2024

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

 First, write the line


 Content-type: text/html plus another blank line, to STDOUT.
After that, write your HTML response page to STDOUT, and it will be sent to the user
when your script is done. That's all there is to it.
o Now, let us understand the way to write CGI programs in Ruby.
o If you want to generate HTML output from a Ruby script, you can write the
following code:
print "HTTP/1.0 200 OK\r\n"
print "Content-type: text/html\r\n\r\n"
print"<html><body>Sucessfully Registred</body></html>\r\n"
Output
 HTTP/1.0 200 OK
 Content-type: text/html
 <html><body>Hello fella! Greetings from IncludeHelp.com</body></html>
 cgi.rb is a predefined class termed as cgi helps you to write CGI programs.
 You can create forms, cookies, maintain stateful sessions and many more, with the
support of cgi class.
 You have to give the statement require cgi at the top of the program to enjoy the
capabilities of cgi class.
Quoting
 If are writing a URL or an HTML code, you are supposed to be very careful with
characters. Many characters have special meaning in URLs. Translations of some of
the characters are given below:
 / =>%2F
 & => %26

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


30
RUBY 20.12.2024

 <space> => +
 To handle the above characters, cgi provides you .escape and .unescape. They are
routines of cgi. See the
 example given below for reference:
require 'cgi'
puts CGI.escape( "He/She must be aware of his/her capabilities & should work accordingly")
Output
He%2FShe+must+be+aware+of+his%2Fher+capabilities+%26+should+ work+accordingly

⚫ he following code will let you know how you can escape HTML special characters?
• puts CGI.escapeHTML( '<a href="/san">Go to the site (Includehelp.com)</a>')
• Output
 &lt;a href=&quot;/san&quot;&gt;Go to the site(Includehelp.com)&lt;/a&gt;
 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
}

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


31
RUBY 20.12.2024

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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


32
RUBY 20.12.2024

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 }

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


33
RUBY 20.12.2024

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 –

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


34
RUBY 20.12.2024

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

Ruby/Tk Widget Classes


 There is a list of various Ruby/Tk classes, which can be used to create a desired GUI
using Ruby/Tk.
 TkFrame Creates and manipulates frame widgets.
 TkButton Creates and manipulates button widgets.
 TkLabel Creates and manipulates label widgets.
 TkEntry Creates and manipulates entry widgets.
 TkCheckButton Creates and manipulates checkbutton widgets
 TkRadioButton Creates and manipulates radiobutton widgets.
 TkListbox Creates and manipulates listbox widgets.
 TkComboBox Creates and manipulates listbox widgets.
 TkMenu Creates and manipulates menu widgets.
 background color and an optional 3-D border to make the frame appear raised or
sunken.

Ruby/Tk Geometry Management


 Geometry Management deals with positioning different widgets as per requirement.
Geometry management in Tk relies on the concept of master and slave widgets.
 A master is a widget, typically a top-level window or a frame, which will contain other
widgets, which are called slaves. You can think of a geometry manager as taking control
of the master widget, and deciding what will be displayed within.
 The geometry manager will ask each slave widget for its natural size, or how large it
would ideally like to be displayed. It then takes that information and combines it with

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


35
RUBY 20.12.2024

any parameters provided by the program when it asks the geometry manager to manage
that particular slave widget.
 There are three geometry managers place, grid and pack that are responsible for
controlling the size and location of each of the widgets in the interface.
 grid Geometry manager that arranges widgets in a grid.
 grid Geometry manager that arranges widgets in a grid
 pack Geometry manager that packs around edges of cavity.
 place Geometry manager for fixed or rubber-sheet placement.

 Ruby/TK - The grid geometry manager


 The grid geometry manager is the most flexible and easy-to-use geometry manager. It
logically divides the parent window or the widget into rows and columns in a two-
dimensional table.
 You can then place a widget in an appropriate row and column format by using the row
and column options, respectively. To understand the use of row and column options,
consider the following example.•
 Syntax
 Here is a simple syntax to create a grid Widget -
 grid('row'=>x, 'column'=>y)
Examples
 Following is the code to display the Label and an Entry widget using the grid geometry
manager-
require 'tk
top=TkRoot.new (title "Label and Entry Widget")
#code to add a label widget
Ib1TkLabel.new(top)(
text 'Hello World
background "yellow" foreground "blue"
grid('row'>0, 'column'=>0)
#code to add a entry widget
el TkEntry.new(top)
background "red" foreground "blue"
grid('row'0, 'column'>1)
Tk mainloop

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


36
RUBY 20.12.2024

Ruby/TK-The pack geometry manager


 The pack geometry manager organizes widgets in rows or columns inside the parent
window or the widget. To manage widgets easily, the pack geometry manager provides
various options, such as fill, expand, and side.
 fill-The fill option is used to specify whether a widget should occupy all the space given
to it by the parent window or the widget. Some of the possible values that can be used
with this option are none, x, y, or both. By default, the fill option is set to none.
 expand - The expand option is used to specify whether a widget should expand to fill
any extra space available. The default value is 0, which means that the widget is not
expanded. The other value is 1.
 side - The side option is used to specify the side against which the widget is to be
packed. Some of the possible values that can be used with this option are top, left,
bottom, or right. By default, the widgets are packed against the top edge of the parent
window.

• Syntax

• Here is a simple syntax to create a pack Widget -


pack('padx'=>10, 'pady'=>10, 'side'=>'left')
require 'tk
top=TkRoot.new (title "Label and Entry Widget"}
#code to add a label widget
Ib1TkLabel.new(top) (
text 'Hello World"
background "yellow"
pack('padx'=>10, 'pady'=>10, 'sideeft)
foreground "blue"
#code to add a entry widget
e1 = TkEntry.new(top) { background "red"
foreground "blue"
pack('padx'=>10, 'pady'=>10, 'side'=>'left')
}
Tk.mainloop
Ruby/TK - The place geometry manager
 The place geometry manager allows you to place a widget at the specified position in
the window. You can specify the position either in absolute terms or relative to the
parent window or the widget.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


37
RUBY 20.12.2024

 To specify an absolute position, use the x and y options. To specify a position relative
to the parent window or the widget, use the relx and rely options.
 In addition, you can specify the relative size of the widget by using the relwidth and
relheight options provided by this geometry manager.

• Syntax
Here is a simple syntax to create a place Widget -

⚫ place(relx'=>x, 'rely'=>y)
Examples
Following is the code which implements the place geometry manager-
require 'tk
top=TkRoot.new (title "Label and Entry Widget"]
#code to add a label widget
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

• Ruby/TK - Canvas Widget

• A Canvas widget implements structured graphics. A canvas displays any number of items,
which may be things like rectangles, circles, lines, and text.

• Syntax
TkCanvas.new {
.....Standard Options.....
.....Widget-specific Options....
}
......Widget-specific Options....
}
Creating Item

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


38
RUBY 20.12.2024

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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


39
RUBY 20.12.2024

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

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


40
RUBY 20.12.2024

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')
TkcLine.new(canvas, 0, 0, 100, 100, 'width' => '2', 'fill' => 'red')

• 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
Here is a simple syntax to create this widget -
TkScrollbar.new {
.....Standard Options....

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC


41
RUBY 20.12.2024

.....Widget-specific Options....
}

• require "tk"

• canvas = TkCanvas.new

• TkcRectangle.new(canvas, '1c', '2c', '3c', '3c', 'outline' => 'black', 'fill' => 'blue')

• TkcLine.new(canvas, 0, 0, 100, 100, 'width' => '2', 'fill' => 'red')


canvas.pack

• Tk.mainloop
Elements of Scrollbar
A scrollbar displays five elements, which are referred in the methods for the scrollbar -
arrow1 - The top or left arrow in the scrollbar.
trough1 The region between the slider and arrow1.
slider - The rectangle that indicates what is visible in the associated widget.
trough2 The region between the slider and arrow2.

• arrow2 - The bottom or right arrow in the scrollbar.


Manipulating the Listbox Items
The insert idx item ?item...? method is used to add one or more items to the list; "idx" is a 0-
based index indicating the position of the item before which the item(s) should be added;
specify "end" to put the new items at the end of the list.
The xview(args) method is used to query and change the horizontal position of the information
in the widget's window.

• S method is used to query and change the vertical position of the text in the widget's window.

Mr. AZMEERA RAMESH (Asst.Prof), CMRTC

You might also like