SL Notes Unit-1
SL Notes Unit-1
Program:
Definition: A complete set of instructions that can be executed independently by a
computer to perform a specific task.
Script:
A set of instructions written in a scripting language designed to automate tasks within
another program is called a script.
Example:
Imagine you want to calculate the area of a rectangle.
Program: You could write a complete C++ program that takes the length and width as
input, performs the calculation, and displays the result. This program would be
compiled and run independently.
Script: You could write a Python script that uses a Python library to perform the
calculation. This script would be executed within a Python interpreter or embedded in
another program to calculate the area dynamically.
Programming Languages:
What is Ruby
Ruby is a dynamic, open source, object oriented and reflective programming language.
Ruby is considered similar to Perl and Smalltalk programming languages. It runs on all
types of platforms like Windows, Mac OS and all versions of UNIX.
Dynamic: In programming languages, "dynamic" typically refers to a language's ability
to execute code and make decisions at runtime, as opposed to compile time. Dynamic
languages allow for flexibility and adaptability during program execution. This can
include dynamic typing (where variables are not assigned a fixed type and can change
during execution), dynamic method invocation (where methods can be called based on
runtime conditions), and dynamic code generation (where new code can be created
and executed during runtime).
Reflective: Reflective programming, on the other hand, refers to a language's ability to
examine and modify its own structure and behavior at runtime. This means that the
program can introspect itself, analyze its own code, and modify its behavior or
structure dynamically while it is running. Reflective languages provide features such as
introspection (examining the properties of objects, classes, or methods at runtime),
intercession (modifying the behavior of objects, classes, or methods at runtime), and
meta-programming (writing code that generates or modifies other code dynamically).
History of ruby:
Ruby was designed and developed by Yukihiro "Martz" Matsumoto in mid 1990s in
Japan.
Why the name Ruby:
The name "Ruby" originated during a chat session between Matsumoto and Keiju
Ishitsuka. Two names were selected, "Coral" and "Ruby". Matsumoto chose the later
one as it was the birthstone of one of his colleagues.
Features of ruby:
❖ Object-oriented
❖ Flexibility
❖ Expressive feature
❖ Mixins
❖ Visual appearance
❖ Dynamic typing and Duck typing
❖ Exception handling
❖ Garbage collector
❖ Portable
❖ Keywords
❖ Statement delimiters
❖ Variable constants
❖ Naming conventions
❖ Keyword arguments
❖ Method names
❖ Singleton methods
❖ Missing method
❖ Case Sensitive
Hello World Program Execution in different languages:
Java Ruby
System.out.println("Hello World");
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:
Statements that are not executed by the interpreter are called Comments.They are
written by a programmer to explain their code so that others who look at the code will
understand it in a better way.
Types of Ruby comments:
1. Single line comment
2. Multi line comment
Single line comment:
The Ruby single line comment is used to comment only one line at a time. They are
defined with # character.
Example:
#This is a single line comment.
i = 10 #Here i is a variable.
puts i
Multiline comment:
The Ruby multi line comment is used to comment multiple lines at a time. They are
defined with =begin at the starting and =end at the end of the line.
=begin
This
is
multi line
comment
=end
*Multiline comment is also known as an embedded document.
Documentation comments (rDoc and ri):
rDoc stands for Ruby Documentation
rDoc is a tool used in Ruby for generating documentation for Ruby code. It allows
developers to document their code in a structured manner using comments, and then
automatically generates HTML or other formats of documentation from those
comments.
ri stands for Ruby Interactive. It's a command-line tool that comes bundled with Ruby. ri
allows you to access documentation for Ruby classes, modules, and methods directly
from the command line.
Example for ri:
Whitespaces:
In Ruby, whitespace refers to any sequence of spaces, tabs, and newline characters in
the code that serve to separate tokens.
Ruby statements are typically terminated by a newline character, indicating the end of a
line of code
Never put a space between a method name and the opening parenthesis.
Syntactic structure
The expression is the most basic unit of syntax in Ruby. The Ruby interpreter is a
programme that evaluates expressions and returns values. Primary expressions, which
represent values directly, are the simplest. Primary expressions include number and
string literals, which were discussed earlier in this chapter. Some keywords, such as
true, false, nil, and self, are also main expressions. Variable references are primary
expressions as well; they evaluate the variable's value.
Compound expressions can be used to express more complex values:
[1,2,3] #An Array literal
{1=>"one", 2=>"two"} #A Hash literal
1..3 #A Range literal
To execute computations on values, operators are utilised, and compound expressions
are created by combining simpler subexpressions with operators:
1 (#A primary expression)
x (#Another primary expression)
x = 1 (#An assignment expression)
x = x + 1 (#An expression with two operators)
Statements like the if statement for conditionally executing code and the while
statement for continually executing code can be created by combining expressions
with Ruby's keywords:
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
Block structure:
Ruby programs have a block structure.
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! " }
In this code, the curly braces and the code inside them are the block associated with
the iterator method invocation 3.times. Formal blocks of this kind may be delimited
with curly braces, or they may be delimited with the keywords do and end:
1.upto(10) do |x|
print x
end
do and end delimiters are usually used when the block is written on more than one line.
To avoid ambiguity with these true blocks, we can call the other kind of block a body
A body is just the list of statements that comprise the body of a class definition, a
method definition, a while loop, or whatever.
Bodies and blocks can be nested within each other, and Ruby programs typically have
several levels of nested code, made readable by their relative indentation. Here is a
schematic example:
module Stats # A module
class Dataset # A class in the module
def initialize(filename) # A method in the class
IO.foreach(filename) do |line| # A block in the method
if line[0,1] == "#" # An if statement in the block
next # A simple statement in the if
end # End the if body
end # End the block
end # End the method body
end # End the class body
end # End the module body
File Structure:
There are only a few rules about how a file of Ruby code must be structured.
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.
#!/usr/bin/ruby
Using __END__:
❖ If a file contains the line __END__ without any whitespace before or after it, the
Ruby interpreter stops processing the file at that point. The rest of the file can
contain arbitrary data that the program can read using the IO stream object
DATA.
Example:
#!/usr/bin/env ruby
# This script calculates the sum of numbers from 1 to 10.
sum = 0
(1..4).each do |n|
sum += n
end
puts "The sum of numbers from 1 to 4 is: #{sum}"
__END__
This is the end of the Ruby script.
To read DATA lines
DATA.each_line do |line|
puts line
end
Program encoding:
❖ Character encoding is a way to represent characters as numbers in binary
format.
❖ Different encoding schemes exist, such as ASCII, UTF-8, UTF-16, ISO-8859-1
(Latin-1), etc.
❖ Each encoding scheme assigns a unique binary code to each character in its
character set.
➢ By default, Ruby assumes that source code is encoded in ASCII, but it can
process files with other encodings as long as they can represent the full
set of ASCII characters.ASCII value for some of the characters are.
➢ #(hash)-35,newline-10,space-10
➢ In Ruby 1.8, you can specify a different encoding with the -K command-
line option. To run a Ruby program that includes Unicode characters
encoded in UTF-8, invoke the interpreter with the -Ku option.
➢ From ruby 1.9 version ,the encoding can be specified using special
comments like # coding: utf-8.
➢ Encoding names are not case-sensitive,ASCII-8BIT,US-ASCII (7-bit
ASCII),ISO-8859-1,the Japanese encoding SHIFT_JIS (also known as SJIS)
and EUC-JP are encoding types.
➢ The encoding comment must be entirely in ASCII and must include the
string "coding" followed by a colon or equals sign and the name of the
desired encoding.
Program Execution:
In Ruby, programs are scripts consisting of statements executed sequentially by
default. There is no special main method like in statically compiled languages. The
Ruby interpreter executes scripts from the first line to the last line, with some
exceptions:
BEGIN and END Statements: Before executing the main body of the script, the
interpreter scans for BEGIN statements and executes their code. Similarly, after
executing the main body, it executes any END statements or registered "shutdown
hook" code using the at_exit function.
Module, Class, and Method Definitions: Unlike in compiled languages where these are
syntactic structures processed by the compiler, in Ruby, they are executable
statements. When encountered, the interpreter executes them, causing the respective
modules, classes, and methods to be defined.
Program Invocation: The Ruby interpreter is invoked from the command line, where it
reads and executes the specified script file. It continues executing until encountering:
● A statement that causes the program to terminate.
● The end of the file.
● A line with the token __END__, marking the logical end of the file.
Package Management with RUBYGEMS:
Gems:
In the RubyGems world, developers bundle their applications and libraries into single
files called gems.
RubyGems:
RubyGems is a standardized packaging and installation framework for libraries and
applications, making it easy to locate, install, upgrade, and uninstall Ruby packages.
or
RubyGems is a big library where you can find and get these packages (gems). It helps
to find, install, and manage the gems in Ruby projects.
RubyGems system provides a command-line tool, appropriately named gem, for
manipulating these gem files.
Installing RubyGems
when you install Ruby, RubyGems will be automatically installed along with it. This is
because RubyGems is the standard package manager for Ruby, and it's essential for
managing libraries and dependencies in Ruby projects.
To check whether RubyGem was installed or not ,use the following command in
command prompt
Rake typically comes pre-installed with Ruby, so you usually don't need to install it
separately. However, if you need to install a specific version or want to ensure you have
the latest version, you can install it using RubyGems, the package manager for Ruby:
❖ -r means remotely
If for some reason—perhaps because of a potential compatibility issue—you wanted
an older version of Rake, you could use RubyGems’ version requirement operators to
specify criteria by which a version would be selected.
Operator Description
= Exact version
!= Any version that is not one mentioned
> Any version that is greater than the one
specified
< Any version that is less than the one specified
>= Any version that is greater than or equal to
specified <= Any version that is less
than or equal to specified
~> Boxed version operator. Version must be
greater than or equal to the specified version
and less than specified version after having its
minor version number increased by one.
Creation of Rakefile and execution:
create a simple Rakefile that defines tasks to greet users in different languages:
Step 2: After successfully installing the csv gem , now we have to use this in our
program.
Create a excel file in any directory and type the data like
# frozen_string_literal: true
require "factorial"
module Factorial
def self.calculate(n)
if n == 0 || n == 1
1
else
n * calculate(n - 1)
end
end
end
Then save the file and close the file
4. Adding Tests and Documentation:
Tests and documentation are essential components of any well-maintained gem. In
test/factorial_test.rb, we write tests to ensure that our calculate method behaves as expected
under different scenarios. Documentation comments in lib/factorial.rb help users understand
how to use the gem and what each method does.
❖ Create a folder test in e:/ruby/factorial.
❖ Create a notepad file(factorial_test.rb) and type the following code
require 'test/unit'
require '../lib/factorial'
class TestFactorial < Test::Unit::TestCase
def test_factorial
assert_equal(1, Factorial.calculate(0))
assert_equal(1, Factorial.calculate(1))
assert_equal(120, Factorial.calculate(5))
assert_equal(3628800, Factorial.calculate(10))
end
end
5. Adding Dependencies:
If your gem relies on other gems or libraries, you specify those dependencies in the gemspec.
For example, if our factorial gem required the bigdecimal gem for handling large numbers, we
would add it as a dependency in the gemspec. This ensures that users can easily install and
use your gem along with its dependencies.
To add a dependency on the bigdecimal gem in your gemspec file, you would include it like
this:
❖ spec.add_dependency 'bigdecimal'
This line tells RubyGems that your gem depends on the bigdecimal gem. When users
install your gem, RubyGems will automatically ensure that the bigdecimal gem is also
installed if it's not already.
6. Ruby Extension Gems:
In some cases, your gem might include C extensions or native code for performance
reasons or to interface with external libraries. You'd need to handle these extensions
properly and specify them in the gemspec to ensure that they're compiled and included
correctly when users install your gem.
7. Building the Gem File:
Once you've defined your gemspec and organized your files, you can use the gem build
command to generate a gem file (.gem). This file contains all the necessary files and
metadata required to distribute your gem.
Open cmd(E:\ruby/factorial) and type the following command
gem build factorial.gemspec
Install Gem Locally: You can install the gem locally to test it in your system.
#!/usr/bin/env ruby
require 'cgi'
cgi = CGI.new
name = "Dev"
puts cgi.header
puts "<html>"
puts "<head>"
puts "<title>CGI Ruby Example</title>"
puts "</head>"
puts "<body>"
puts "<h1>Hello, #{name.empty? ? 'Anonymous' : name}!</h1>"
puts "</body>"
puts "</html>"
Save the file in the cgi-bin directory within your XAMPP installation. For example,
you can save it in C:\xampp\cgi-bin.
8. Set Executable Permission:
Right-click on the hello.rb file, select "Properties," and then go to the "Security"
tab.
Click on "Edit" to change permissions, and make sure that "Read & execute" is
checked for the appropriate user group (e.g., Everyone).
9. Access the CGI Script via Web Browser:
Open a web browser and navigate to http://localhost/cgi-bin/hello.rb.
You should see the output of your CGI script displayed in the browser window.
Example 2:
Create html file in cgi-bin folder and name of the file is index.html
<!DOCTYPE html>
<head>
<title>CGI Ruby Example</title>
</head>
<body>
<h1>Enter Your Name</h1>
<form action="name.rb" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Create ruby file same folder i.e in cgi-bin and name it with name.rb
name.rb
#!/usr/bin/env ruby
require 'cgi'
cgi = CGI.new
name = cgi['id']
puts cgi.header
puts "<html>"
puts "<head>"
puts "<title>CGI Ruby Example</title>"
puts "</head>"
puts "<body>"
puts "<h1>Hello, #{name.empty? ? 'Anonymous' : name}!</h1>"
puts "</body>"
puts "</html>"
Open any browser window and execute the html file http://localhost/cgi-bin/index.html
erb:
ERB stands for Embedded RuBy. It's a feature in Ruby that allows you to embed Ruby
code within a text document, typically used for generating dynamic content in web
applications. ERB is commonly used in web frameworks like Ruby on Rails for
generating HTML pages dynamically.
With ERB, you can write plain text documents (often HTML or XML) with snippets of
Ruby code embedded within <% %> or <%= %> tags. Here's a brief explanation of the
two main types of ERB tags:
<% %> (ERB scriptlet tags): These tags are used to embed Ruby code that doesn't
output anything directly to the document. They are typically used for control structures
like loops and conditionals.
<%= %> (ERB output tags): These tags are used to embed Ruby code that outputs a
value to the document. The result of the Ruby expression inside these tags will be
included in the output document.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<% if @logged_in %>
<p>Welcome back, <%= @username %>!</p>
<% else %>
<p>Welcome, Guest!</p>
<% end %>
</body>
</html>
Cookies:
cookies are small pieces of data that websites store on your device. They act like
memory for websites, enabling them to remember things about you and your browsing
activity.
Working of cookies:
1. Visiting a website: When you visit a website for the first time, the web server
may send your browser a cookie.
2. Storing the cookie: Your web browser stores the cookie information on your
device, typically in a file.
3. Subsequent visits: When you revisit the same website, your browser sends the
stored cookie back to the web server.
This exchange of cookies allows websites to:
❖ Maintain user sessions: Cookies can remember if you're logged in or not,
eliminating the need to re-enter credentials every time you visit a page.
❖ Personalize your experience: Websites can use cookies to tailor content and
functionality based on your preferences or past behavior. For instance, an e-
commerce site might use cookies to recommend products you might be
interested in.
❖ Track user behavior: Cookies can be used to track what pages you visit and how
you interact with a website. This data is often used for analytics purposes or
targeted advertising.
Example:
require 'cgi'
cgi = CGI.new
# Read the value of the 'username' cookie
username_cookie = cgi.cookies['Deepak']
puts cgi.header
if username_cookie.empty?
# Create cookie if it doesn't exist
new_cookie = CGI::Cookie.new('name' => 'Dev', 'value' => 'Guest', 'expires' => Time.now
+ 3600) # Expires in 1 hour
puts new_cookie
puts "Content-Type: text/html\n\n"
puts "<html>"
puts "<body>"
puts "<h1>Welcome, Guest!</h1>"
puts "<p>A 'Dev' cookie has been set.</p>"
puts "</body>"
puts "</html>"
else
# Greet user with stored username if cookie exists
username = username_cookie.first.value
puts "Content-Type: text/html\n\n"
puts "<html>"
puts "<body>"
puts "<h1>Welcome back, #{username}!</h1>"
puts "<p>You have returned to our site.</p>"
puts "</body>"
puts "</html>"
end
Choice of Web Servers:
WEBrick is a small, simple HTTP server toolkit that comes bundled with Ruby. It's often
used for development and testing purposes due to its ease of use and lightweight
nature. WEBrick is written in Ruby and provides a basic but functional web server that
can serve both static and dynamic content.
Here's a simple example of how you can use WEBrick to create a basic web server in
Ruby:
require 'webrick'
# Define a class for handling requests
class MyHandler < WEBrick::HTTPServlet::AbstractServlet
def do_GET(request, response)
# Set the response content type
response.content_type = 'text/plain'
# Set the response body
response.body = "Hello, World! You requested: #{request.path}"
# Send the response
response.status = 200
end
end
# Create a server instance
server = WEBrick::HTTPServer.new(Port: 8000)
# Mount the handler to respond to requests
server.mount '/', MyHandler
# Trap signals to gracefully shutdown the server
trap('INT') { server.shutdown }
# Start the server
server.start
You can save this code in a file (e.g., simple_server.rb) and then run it using Ruby. After running the
script, open any browser and type the at http://localhost:8000 and see the response "Hello, World! You
requested: /".
1. The service requester creates a SOAP message containing details about the
service it wants to invoke and any relevant data.
2. The SOAP message is sent to the service provider using HTTP (Hypertext
Transfer Protocol).
3. The service provider receives the SOAP message, parses the XML data, and
executes the requested service.
4. The service provider generates a response SOAP message containing the
results of the service execution.
5. The response message is sent back to the service requester using HTTP.
6. The service requester parses the response message and uses the extracted
data.
● Complexity: SOAP messages can be complex and verbose due to the XML
structure, leading to increased processing overhead.
● Performance: Compared to simpler protocols like REST (Representational State
Transfer), SOAP can be slower due to the parsing of XML data.
● Steeper Learning Curve: Developing SOAP web services requires understanding
the SOAP protocol, XML, and potentially WSDL, which can have a steeper
learning curve.
Applications of rubytk:
RubyTk shines in creating desktop applications with graphical user interfaces (GUIs)
for various purposes. Here are some common applications of RubyTk:
1. Develop basic productivity tools like calculators, note-taking apps, to-do list
managers, file launchers.
2. Create custom configuration or settings windows for other programs.
3. Design data visualization tools to display information in a user-friendly format
(charts, graphs).
4. Design data management interfaces for CRUD (Create, Read, Update, Delete)
operations on databases.
Example: Open notepad and the following code and save the file with tkexample.rb
Open command prompt and execute the ruby file
ruby tkexample.rb
require 'tk'
root = TkRoot.new { title "First Application" }
TkLabel.new(root) do
text 'Hello, World!'
pack('padx' => 15, 'pady' => 15, 'side' => 'left')
end
Tk.mainloop
Output:
Widgets
Widgets in Tk Ruby refer to the various graphical elements(Components) you can
create to build a graphical user interface (GUI) for your Ruby applications. These
widgets serve as the building blocks for creating interactive and visually appealing
interfaces. Some common widgets include buttons, labels, entry fields, checkboxes,
radio buttons, listboxes, and frames.
Each widget has its own set of properties and methods that allow you to customize its
appearance and behavior. For example, you can set the text displayed on a button,
define actions to be performed when a button is clicked, or specify the layout and
alignment of widgets within a window.
To create a Tk widget instance, add "Tk" to the widget's name, like TkLabel, TkButton,
or TkEntry, and then use the new method to initialize it.
TkEntry:
require 'tk'
root=TkRoot.new{title "entry"}
TkEntry.new(root){
width 30
pack('padx'=>300,'pady'=>10)
}
Tk.mainloop
Output:
TkButton:
require 'tk'
root=TkRoot.new{title "button example"}
TkButton.new(root){
text "Submit"
foreground 'red'
font TkFont.new(size:18,family:"Arial Black")
relief 'flat'
pack
}
Tk.mainloop
Output:
Distances (as in the padx and pady options in these examples) are assumed to
be in
pixels but may be specified in different units using one of the suffixes c
(centimeter), i
(inch), m (millimeter), or p (point). "12p", for example, is twelve points.
Getting Widget Data
We can get information back from widgets by using callbacks and by binding
variables.
Callbacks are very easy to set up.
Callback typically refers to a function or block of code that gets executed in
response to a specific user action or event, such as clicking a button, typing in a
text field, or selecting an item from a list.
For example, when you set up a callback for a button click event in Tk Ruby,
you're essentially specifying what code should be executed when the button is
clicked. This code is encapsulated within a Proc object and passed to the
command option of the TkButton widget. When the button is clicked, the
callback (i.e., the code specified in the Proc object) gets executed.
When an event, such as clicking a button, occurs in Tk Ruby, the Proc object
associated with the event (often specified using the command option) is indeed
responsible for executing the lines of code defined within it. So, in the case of a
button click event, the Proc object's responsibility is to execute the code
specified in the command option, which typically includes the actions to be
taken in response to the button click.
Example:
require 'tk'
TkButton.new do
text "EXIT"
command { exit }
pack('side'=>'left', 'padx'=>10, 'pady'=>10)
end
Tk.mainloop
Common Options:
❖ text: Change the displayed text in labels, buttons, etc.
❖ font: Modify the font style and size.
❖ background: Set the background color.
❖ foreground: Set the text color.
❖ width: Define the width of the widget in pixels or characters.
❖ height: Define the height of the widget in pixels.
❖ state: Control the widget's state (e.g., :disabled, :normal).
❖ relief: Set the border style (e.g., :flat, :raised, :groove).
Example:
require 'tk'
root = TkRoot.new { title "Ex3" }
lbl = TkLabel.new(root) do
justify 'center'
text 'Hello, World!'
pack('padx'=>5, 'pady'=>5, 'side' => 'top')
end
TkButton.new(root) do
text "Ok"
command { exit }
pack('side'=>'left', 'padx'=>10, 'pady'=>10)
end
TkButton.new(root) do
text "Cancel"
command { lbl.configure('text'=>"Goodbye, Cruel World!") }
pack('side'=>'right', 'padx'=>10, 'pady'=>10)
end
Tk.mainloop
Output:
When we click on cancel the label content will be changed.
Geometry Management:
Geometry management refers to the process of arranging and positioning widgets
within a window. It plays a crucial role in defining the layout and visual structure of
your application. Tk provides three main geometry managers:
1. Pack
2. Grid
3. Place
Pack:
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.
Here is a simple syntax to create a pack Widget −
pack('padx'=>10, 'pady'=>10, 'side'=>'left')
Example:
require 'tk'
top = TkRoot.new {title "Label and Entry Widget"}
#code to add a label widget
lb1 = TkLabel.new(top) {
text 'Hello World'
background "yellow"
foreground "blue"
pack('padx'=>200, 'pady'=>50, 'side'=>'top')
}
#code to add a entry widget
e1 = TkEntry.new(top) {
background "red"
foreground "blue"
pack('padx'=>100, 'pady'=>10, 'side'=>'top')
}
Tk.mainloop
Output:
Grid:
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.
Syntax:
grid('row'=>x, 'column'=>y)
Example:
require 'tk'
# Create a Tk root window
root = TkRoot.new { title "Grid Layout Example" }
# Create labels
label1 = TkLabel.new(root) { text 'Label 1'; background 'red' }
label2 = TkLabel.new(root) { text 'Label 2'; background 'green' }
label3 = TkLabel.new(root) { text 'Label 3'; background 'blue' }
# Arrange labels using grid geometry manager
label1.grid('row' => 0, 'column' => 0)
label2.grid('row' => 0, 'column' => 1)
label3.grid('row' => 1, 'column' => 0)
# Start the Tk event loop
Tk.mainloop
Output:
Place:
The place geometry manager allows you to place a widget at the specified position in
the window. You can specify the position either in absolute terms or relative to the
parent window or the widget.
To specify an absolute position, use the x and y options. To specify a position relative
to the parent window or the widget, use the relx and rely options.
In addition, you can specify the relative size of the widget by using the relwidth and
relheight options provided by this geometry manager.
Syntax
place(relx'=>x, 'rely'=>y)
Example:
require 'tk'
# Create a Tk root window
root = TkRoot.new { title "Place Layout Example" }
# Create labels
label1 = TkLabel.new(root) { text 'Label 1'; background 'red' }
label2 = TkLabel.new(root) { text 'Label 2'; background 'green' }
label3 = TkLabel.new(root) { text 'Label 3'; background 'blue' }
# Place labels using place geometry manager
label1.place('x' => 10, 'y' => 10)
label2.place('x' => 50, 'y' => 50)
label3.place('x' => 100, 'y' => 100, 'width' => 100, 'height' => 50)
# Start the Tk event loop
Tk.mainloop
Output:
Binding Events
"bind" refers to the process of associating an event with a specific action or callback
function. When an event occurs, such as a mouse click, keypress, or window resize, the
associated action or function is executed.
Syntax:
widget.bind(event, callback_function)
❖ widget: The widget to which the event is bound.
❖ event: The event to bind, specified as a string (e.g., "<Button-1>" for left mouse
click).
❖ callback_function: The function to be called when the event occurs.
Example:
require 'tk'
root=TkRoot.new
b=TkButton.new(root)do
text "Click here"
pack
end
l=TkLabel.new(root)do
text "This text will be changed"
pack
end
l.focus
b.command{l.configure(text:"changed")}
l.bind("Key-a"){l.configure(background:"red")}
Tk.mainloop
Canvas:
Canvas widget is used to draw graphical elements such as lines, rectangles, circles,
and text in a window.
Example:
require 'tk'
root = TkRoot.new
canvas = TkCanvas.new(root) do
width 300
height 200
background 'white'
pack
end
# Draw a rectangle (x,y,width,height)
rectangle = canvas.create('rectangle', 50, 50, 200, 150, fill: 'blue')
# Draw an oval()
oval = canvas.create('oval', 100, 100, 250, 200, fill: 'red')
# Draw a line
line = canvas.create('line', 20, 30, 200, 100, fill: 'green')
Tk.mainloop
Output:
Scrolling:
Scrolling in Ruby TK allows you to view content that's larger than the visible area of a
widget like a text box or a frame. Here's a breakdown of how it works:
require 'tk'
begin
root = TkRoot.new
text = TkText.new(root) { width 40; height 10 }
text.insert('end', "This is a much shorter text.\n" *100)
scroll_bar = TkScrollbar.new(root)
text.yscrollcommand(scroll_bar.method(:set))
scroll_bar.command(proc { |*args| text.yview(*args) })
scroll_bar.pack(side: 'right', fill: 'both', expand: true)
text.pack(side: 'left', expand: true, fill: 'both')
Tk.mainloop
end