SL Imps 1,2,3
SL Imps 1,2,3
Features of Ruby
2. Dynamic Typing: Ruby is dynamically typed, meaning you don’t need to specify
data types explicitly. Type checks are done at runtime.
3. Garbage Collection: Ruby has automatic garbage collection, which helps manage
memory by automatically removing unused objects.
7. Extensive Standard Library: Ruby comes with a rich set of built-in libraries and
modules for various tasks, from le handling to web programming.
8. Block and Iterators: Ruby supports blocks, iterators, and closures, which are
powerful tools for iterating over collections and working with anonymous functions.
Understanding the structure and execution ow of Ruby code is essential for effective
programming. Ruby's design emphasizes simplicity and readability, and its execution model
re ects this philosophy.
1. Lexical Analysis
Lexical analysis is the rst phase of interpreting or compiling Ruby code. It involves
breaking down a sequence of characters in the source code into meaningful tokens. These
tokens are the smallest units of meaning in a language.
1
fl
fi
fi
fi
fi
fi
fl
fi
fi
Key Components:
1. Tokens: Basic building blocks of the code, such as keywords, operators, literals, and
identi ers.
◦ Whitespace: Spaces, tabs, and newlines that separate tokens but are otherwise
ignored.
◦ Comments: Text ignored by the interpreter, used for documentation. Ruby
supports single-line # and multi-line =begin ... =end comments.
3. Example of Tokenization:
x = 10 + 20
◦ Tokens: x, =, 10, +, 20
2. Syntactic Structures
Syntactic analysis (or parsing) involves analyzing tokens according to the grammatical rules
of Ruby. This phase checks whether the sequence of tokens forms a valid Ruby program
structure.
1. Expressions:
◦ Arithmetic: a + b, 3 * 5
◦ Logical: x && y, !flag
2. Statements:
if age > 18
◦ puts "Adult"
◦ else
◦ puts "Minor"
◦ end
2
fi
fi
◦
3. Blocks:
◦ Methods and Blocks: Methods can be de ned and invoked with arguments.
Blocks can be passed to methods.
def greet(name)
◦ "Hello, #{name}!"
◦ end
◦
◦ puts greet("Alice")
◦
class Person
◦ def initialize(name)
◦ @name = name
◦ end
◦
◦ def say_hello
◦ "Hello, #{@name}"
◦ end
◦ end
◦
def add(a, b)
◦ a + b
◦ end
3. Program Execution
Program execution is the phase where the Ruby interpreter processes the parsed code and
performs the actions de ned by the program.
3
fi
fi
fi
fi
fi
Key Steps in Execution:
1. Loading Code:
◦ Ruby scripts or les are loaded into memory. This involves reading the source
code and preparing it for execution.
2. Parsing and Compiling:
◦ The Ruby interpreter parses the code to check for syntax errors and compiles it
into an internal representation (such as an Abstract Syntax Tree or AST).
3. Interpreting Code:
RubyGems is a system for managing Ruby libraries, called gems. A gem is a package that
includes Ruby code, and optionally, other resources like con guration les and
documentation. RubyGems allows developers to easily install, update, and manage these
libraries in their Ruby environment.
Key Concepts
Gems:
4
fi
fi
fi
fi
◦ Metadata: Information like the gem’s name, version, and dependencies
(de ned in gemspec le).
1. Installing RubyGems
RubyGems is typically included with Ruby installations. You can check if it's installed and
view its version with:
gem --version
If it’s not installed, you can install it manually by following the instructions on the
RubyGems website.
2. Basic Commands
gem update
gem list
5
fi
fi
fi
• Search for Gems: To search for a gem by name or keyword:
For managing gem dependencies in a Ruby project, it's common to use a Gemfile along
with the Bundler gem:
• Gem le: This le speci es the gems required for your project. Create a Gemfile in
your project’s root directory with the following format:
source 'https://rubygems.org'
• Bundler: To install the gems listed in the Gemfile, you use Bundler. First, install
Bundler if you haven’t already:
•
Then, run:
bundle install
•
To update gems speci ed in the Gemfile, use:
bundle update
•
You can also use Bundler to execute commands in the context of your bundled gems:
• Check Gem Info: To see information about a gem, including its version and
dependencies:
gem info gem_name
6
fi
fi
fi
fi
fi
fi
• Find Gem Versions: To see all available versions of a gem:
gem list -r gem_name
If you want to create your own gem, you can use the bundler command to generate the
necessary les:
This command creates a new gem with a default structure. You’ll nd the gem's code in the
lib/ directory and can add tests, documentation, and other les as needed.
6. Publishing a Gem
To share your gem with the community, you need to push it to RubyGems.org:
Make sure to sign up for a RubyGems.org account and con gure your credentials on your
local machine before pushing gems.
CGI Script:
7
fi
fi
fi
fi
fi
fi
1. Execution Model: When a web server receives a request for a CGI script, it executes
the script and returns the output as part of the HTTP response.
2. Languages: CGI scripts can be written in various programming languages, including
Perl, Python, Ruby, PHP, and shell scripting.
3. Interaction: CGI scripts can handle data sent via HTTP GET or POST methods and
can set or read cookies to manage user sessions.
Writing CGI Scripts in Ruby
• Install Ruby: Ensure Ruby is installed on your system. You can check by running
ruby -v in your terminal.
• Web Server Con guration: Your web server needs to be con gured to execute CGI
scripts. For example, with Apache, ensure that the mod_cgi module is enabled and
that the CGI directory is properly set up (often /cgi-bin/).
2. Creating a Simple CGI Script
#!/usr/bin/env ruby
require 'cgi'
cgi = CGI.new
#!/usr/bin/env ruby
8
fi
fi
fi
fi
require 'cgi'
cgi = CGI.new
name = cgi['name'] # Retrieves 'name' parameter from
form data
#!/usr/bin/env ruby
require 'cgi'
cgi = CGI.new
cookies = cgi.cookies
name = cookies['name'] ? cookies['name'].first : 'Guest'
# Setting cookies
cookie = CGI::Cookie.new('name', 'JohnDoe', path: '/')
9
fi
fi
• Accessing Scripts: Test your CGI scripts by navigating to the appropriate URL in
your web browser (e.g., http://yourserver/cgi-bin/hello.rb).
• Error Logs: Check your web server’s error logs if you encounter issues.
A cookie is a small piece of data sent from a web server and stored on a user's device by their
web browser. Cookies are used to maintain state and store information across multiple
requests from the same user. They enable functionalities such as session management, user
preferences, and tracking.
Ruby’s CGI library includes the CGI::Cookie class for creating, reading, and managing
cookies.
To create a cookie object and store some text in it using Ruby's CGI library
Script:
#!/usr/bin/env ruby
require 'cgi'
cgi = CGI.new
10
fi
fi
fi
cookie = CGI::Cookie.new(
name: 'my_cookie',
path: '/',
Explanation
1. Set Up:
◦ #!/usr/bin/env ruby: Tells the system to use Ruby to run the script.
◦ require 'cgi': Loads the CGI library to handle web requests.
2. Create Cookie:
1. Web Services
11
fi
• De nition: Web services are methods that allow different software applications to
communicate over the internet. They help different systems interact and share data,
regardless of the programming language or platform used.
Key Points:
• Communication: They use standard web protocols to send and receive data.
• Data Formats: Commonly use XML or JSON to structure the data.
Example: A weather application on your phone might use a web service to get weather data
from a remote server.
• Messages: SOAP messages are formatted in XML and include an envelope that wraps
around the data and instructions.
• Transport: Typically operates over HTTP/HTTPS (the same protocols used for web
browsing).
Installation of SOAP4R
SOAP4R is a Ruby library used to work with SOAP web services. It allows Ruby
applications to interact with SOAP-based services by generating and parsing SOAP
messages.
Installation Steps:
1. Ensure Ruby is Installed: Make sure you have Ruby installed on your system. You
can check by running:
ruby -v
Here’s a simple example to create a SOAP server using SOAP4R. This server provides a
service that returns a greeting message.
12
fi
fi
fi
require 'soap/rpc/standaloneServer'
RubyTk is a toolkit that allows you to create graphical user interfaces (GUIs) for Ruby
applications. It’s a Ruby binding for the Tk GUI toolkit, which is used to build desktop
applications with windows, buttons, text elds, and other UI elements.
1. Install RubyTk
RubyTk is usually bundled with Ruby, so you may not need to install it separately. To check
if you have it, try running a simple Tk script. If you encounter issues, you might need to
install the Tk development libraries for your operating system.
2. Basic Tk Application
require 'tk'
13
fi
fi
# Create the main window
root = TkRoot.new { title "Simple Tk App" }
Explanation:
Q.Ruby on Rails
Ruby on Rails (often simply called Rails) is a powerful web application framework written
in Ruby. It simpli es the process of building web applications by providing a structured way
to develop and organize code. Here’s a basic overview:
Key Concepts:
14
fi
fi
fi
fi
Key Features
1. MVC Architecture: Separates code into Models (data), Views (UI), and Controllers
(logic).
2. Active Record: Manages database interactions using Ruby objects.
3. Convention over Con guration: Reduces setup by providing sensible defaults.
4. Scaffolding: Automatically generates code for basic CRUD operations.
5. Routing: Maps URLs to controller actions.
Pros
Cons
When working with memory in Ruby extensions, especially for tasks that involve large data
structures or objects not directly used by Ruby, you need to use speci c memory allocation
routines to ensure proper integration with Ruby’s garbage collector.
1. ALLOC_N(c-type, n)
◦ Purpose: Allocates memory for n objects of type c-type.
◦ Usage: ALLOC_N(type, 10) allocates memory for an array of 10
elements of type type.
◦ Example: int *array = ALLOC_N(int, 100);
2. ALLOC(c-type)
15
fi
fi
fl
fi
◦ Purpose: Allocates memory for a single object of type c-type and casts the
result.
◦ Usage: ALLOC(type) allocates memory for one object of type type.
◦ Example: type *ptr = ALLOC(type);
3. REALLOC_N(var, c-type, n)
◦ Purpose: Reallocates memory for n objects of type c-type and assigns it to
var.
◦ Usage: REALLOC_N(ptr, type, 20) reallocates memory for 20
objects of type type.
◦ Example: array = REALLOC_N(array, int, 200);
4. ALLOCA_N(c-type, n)
◦ Purpose: Allocates memory for n objects of type c-type on the stack. This
memory is automatically freed when the function returns.
◦ Usage: ALLOCA_N(type, 5) allocates memory for 5 objects of type
type on the stack.
◦ Example: type *stack_array = ALLOCA_N(type, 10);
• Garbage Collection: Ruby uses a garbage collector to manage memory for Ruby
objects. When allocating memory for large data structures or objects not managed by
Ruby, use the above routines to ensure proper integration with the garbage collector.
• Automatic Release: Ruby may release memory back to the operating system
depending on the implementation of malloc used by the OS.
Storage Allocation Strategies
1. Static Allocation:
◦ Description: Allocates storage for all data objects at compile time. The size
and location of storage are xed and known before execution begins.
◦ Use Case: Constants and global variables in C.
2. Stack Allocation:
1. Check Gems: Remove unused gems from the Gem le and check for memory leak
reports in the issue trackers of remaining gems.
16
fi
fl
fi
2. Run Rubocop: Use the rubocop-performance extension to identify potential
performance issues, including memory leaks.
3. Code Review: Manually review the Ruby code for practices that may cause memory
leaks, such as unintentional global variables or improper handling of resources.
Ruby is a dynamically typed language, meaning that the types of variables and object
properties are determined at runtime. This exibility allows for rapid development and
simpler code but can introduce challenges in maintaining and scaling larger codebases.
Key Concepts
◦ Dynamic Typing: Types are determined during execution, allowing for more
exible and quicker coding but making it harder to enforce type constraints
and maintain large codebases.
◦ Static Typing: Types are checked at compile time, providing more structure
but requiring more upfront design and less exibility.
2. Duck Typing:
17
fl
fi
fi
fi
fi
fi
fi
fi
fi
fl
fl
fl
fi
◦
Usage: Facilitates guided duck typing, making it clearer what methods are
expected and improving code safety.
5. Non-uniformity:
◦
De nition: A pattern where expressions or variables can hold values of
different types. Common in Ruby, such as variables holding instances of
different classes or methods returning different types.
◦ Challenges: Can lead to confusion and bugs due to unexpected type
variations.
Bene ts of Ruby Type System Enhancements
◦
Type checking can help detect unde ned method calls, constant references,
and other issues that dynamic typing might miss.
2. Nil Safety:
◦
Type checkers using RBS can handle optional types, identifying when values
can be nil and preventing errors like calling methods on nil.
3. Better IDE Integration:
◦
IDEs can leverage RBS les to provide better code completions, faster error
reporting, and more reliable refactoring.
4. Guided Duck Typing:
◦ Interface types guide what methods an object should support, making APIs
clearer and safer, and enhancing the bene ts of duck typing while reducing its
risks.
• Embedding Ruby into other languages or environments can leverage the strengths of Ruby
while still utilizing lower-level languages or integrating with existing libraries.
• Embedding Ruby into other languages combines the ease of Ruby with the performance
and capabilities of lower-level languages like C/C++ or Java.
• These integrations allows developers to optimize critical parts of their applications, reuse
existing libraries, and leverage the strengths of multiple programming environments.
• Whether through any extension, Ruby provides versatile methods to extend and enhance its
functionality.
18
fi
fi
fi
fi
fi
Reasons for Embedding Ruby
1. Performance Optimization:
◦
Speed: Critical parts of the program that require high performance can be
implemented in a lower-level language like C or C++.
◦ Ef ciency: Use specialized libraries or algorithms that are already
implemented in other languages.
2. Library Integration:
◦
Access Existing Libraries: Use libraries written in C, C++, or Java that are
not available in Ruby.
◦ Reuse Code: Leverage well-tested, optimized code from other languages to
enhance Ruby applications.
3. Complex Systems:
1. Ruby C Extensions:
◦ Purpose: Allows you to write C code that can be called from Ruby, extending
Ruby’s functionality with performance-critical or specialized features.
◦ Bene ts: Integrates closely with Ruby, making it easy to call C functions and
use C data structures from Ruby code.
◦ Example: Writing a C extension to provide a faster implementation of a
computationally intensive algorithm.
#include "ruby.h"
// Example C function
VALUE fast_method(VALUE self) {
return INT2NUM(42); // Returns integer 42 to Ruby
}
19
fi
fi
fi
fi
fi
2. JRuby:
◦ Purpose: Runs Ruby code on the Java Virtual Machine (JVM) and allows
Ruby to interact with Java libraries and classes.
◦ Bene ts: Integrates Ruby with Java’s extensive ecosystem and libraries.
◦ Usage: Use Java classes and methods directly from Ruby code.
list = ArrayList.new
list.add("Hello")
puts list.get(0) # Outputs "Hello"
• Embedding Ruby involves integrating the Ruby interpreter into a C/C++ application,
allowing Ruby code to be executed within the context of the application.
• Embedding Ruby into a C/C++ application allows you to execute Ruby code from within
your application.
• The key steps involve initializing the Ruby interpreter, setting options, loading Ruby
scripts, and running the interpreter as needed.
Basic Example
#include "ruby.h"
int main() {
ruby_init();
/* Load a Ruby le */
rb_load_ le("start.rb");
20
fi
fi
fi
1. ruby_init()
◦ Purpose: Sets the script name ($0) and can affect Ruby’s behavior.
◦ Usage: Use to specify the name of the Ruby script for logging or debugging
purposes.
4. rb_load_file(char *file)
◦ Purpose: Runs the Ruby interpreter. It processes any pending Ruby code.
◦ Usage: Call this to execute Ruby code that has been loaded or queued for
execution.
◦
Scripting languages are programming languages designed to automate tasks, control software,
or enhance other programs. They are usually interpreted rather than compiled, meaning they
run directly from the source code without needing a separate compilation step.
1. Early Days: Began in the 1950s and 1960s with Unix shell scripts for automating
system tasks.
2. Bourne Shell: Introduced in the 1970s for Unix, simplifying system administration.
3. Perl: Developed in the late 1980s for text processing and system tasks.
4. Python: Created in the late 1980s, focused on readability and versatility.
5. JavaScript: Introduced in the mid-1990s to enhance web page interactivity.
6. Ruby: Created in the mid-1990s, known for its elegant syntax and web development
use.
21
fi
fi
Characteristics
Scripting languages are high-level programming languages designed for automating tasks and
manipulating data with concise, readable code. They are often interpreted rather than
compiled, making them ideal for rapid development and integration.
Scripting languages are versatile tools employed in a wide range of applications, from
modern visual interfaces to traditional system tasks. Users of scripting languages can be
categorized into two main types: modern applications and traditional users.
1. Visual Scripting:
◦ Purpose: Create graphical interfaces and applications.
22
fi
fi
◦ Examples: Visual Basic for developing applications, enhancing web pages
with graphical elements.
2. Scripting Components:
1. System Administration:
◦ Purpose: Automate administrative tasks and manage systems.
◦ Examples: Shell scripting for task automation and system con guration.
2. Experimental Programming:
23
fi
fl
fi
▪ Python: Versatile and used for system scripting, web development, and
more.
▪ Tcl: Often used with C/C++ extensions for embedded scripting.
Web scripting is a crucial aspect of web development, allowing for the automation of tasks
and the creation of dynamic, interactive web pages.
Web is the most fertile areas for the application of scripting languages. Web scripting
divides into three areas
a. Processing Forms
In the early days of the web, when a user submitted a form, the data entered would be sent to
the server where a Common Gateway Interface (CGI) script processed it. This script would
then generate an HTML page as a response, which would be sent back to the user's browser.
• Server-Side Processing: The data goes to the server where a script (like Perl or Python)
processes it and creates a new web page to show you.
• Client-Side Validation: Before sending the data to the server, scripts like JavaScript can
check if the information is correct to prevent errors.
Dynamic HTML (DHTML) enables more interactive and engaging web pages by making the
elements on a page scriptable. This allows for:
• Interactive Elements: JavaScript or VBScript can change what you see on a page (like
showing or hiding elements) without reloading the whole page.
• ActiveX Controls: Special objects from Microsoft that add more complex features to web
pages.
Dynamic HTML generation involves creating web pages on the server side before sending
them to the client. This is often used for:
• Database Content: Scripts generate web pages using information from a database (like
showing search results).
• Server-Side Scripting: Technologies like ASP or PHP create and customize web pages
based on data from the server.
24
Q.Explain PERL: Names and values, variables, scalar
expressions
Perl is a high-level, general-purpose programming language known for its versatility and
power. It was developed by Larry Wall and rst released in 1987. Perl is often used for tasks
such as text processing, system administration, web development, and network programming.
• Names: In Perl, identi ers (names) are used to refer to variables, functions, and other
elements. These names usually start with a letter or underscore and can include
numbers but cannot start with a number. For example, $variable_name is a
valid name for a scalar variable.
• Values: Values are the actual data stored in variables. They can be numbers, strings,
or references to other data structures.
Variables
Scalar expressions are operations that work with scalar values (single values). Some
examples include:
25
fi
fi
◦ Example: $greeting = "Hello" . " World"; (where
$greeting will be "Hello World").
• Comparison Operations: Comparing scalar values.
In Perl, a basic script using these concepts might look like this:
# Scalar variables
$name = "Alice";
$age = 30;
# Array variable
@colors = ('red', 'green', 'blue');
# Hash variable
%person = ('name' => $name, 'age' => $age);
# Scalar expressions
$greeting = "Hello, " . $person{'name'};
$sum = 10 + 20;
# Print values
print "$greeting\n"; # Outputs: Hello, Alice
print "Sum: $sum\n"; # Outputs: Sum: 30
control structures, arrays, lists, hashes, strings, pattern matching, and regular expressions in
Perl:
Control Structures
1. Conditional Statements:
◦ if / elsif / else:
if ($condition) {
# Code to execute if condition is true
} elsif ($other_condition) {
# Code to execute if the other condition is true
} else {
# Code to execute if no conditions are true
26
fl
2. Loops:
for:
for (my $i = 0; $i < 10; $i++) {
print "$i\n";
}
foreach:
foreach my $item (@array) {
print "$item\n";
}
while:
while ($condition) {
# Code to execute while condition is true
}
do...while:
do {
# Code to execute
} while ($condition);
next: Skips the rest of the current loop iteration and moves to the next
iteration.
next;
1. Arrays:
27
Declaration and Initialization:
@colors = ('red', 'green', 'blue');
Accessing Elements:
$first_color = $colors[0]; # ‘red'
Array Operations:
push(@colors, 'yellow'); # Adds 'yellow' to
the end of @colors
2. Lists:
◦ Lists are essentially arrays in context but can also be used for direct
assignment.
◦ Creating a List:
Hashes
1. Hashes:
◦ Hashes are unordered collections of key-value pairs.
Strings
1. String Operations:
Concatenation:
$greeting = "Hello, " . "World!";
Interpolation:
$name = "Alice";
$message = "Hello, $name!";
String Functions:
$length = length($message); # Returns the
28 length of the string
Pattern Matching and Regular Expressions
1. Pattern Matching:
if ($string =~ /pattern/) {
print "Match found!\n";
}
For Substitution :
$string =~ s/pattern/replacement/;
2. Regular Expressions:
◦ Regular expressions are powerful tools for matching and manipulating strings.
◦ Basic Regex:
◦ Common Metacharacters:
▪ .: Matches any single character
▪ \d: Matches any digit
▪ \w: Matches any word character
▪ *: Matches zero or more of the preceding element
▪ +: Matches one or more of the preceding element
▪ ?: Matches zero or one of the preceding element
Introduction to Perl
Perl is a versatile, high-level programming language created by Larry Wall in 1987. Known
for its text-processing capabilities, Perl is widely used for scripting, system administration,
and web development. Although there's no of cial full form, it is often expanded as "Practical
29
fi
Extraction and Reporting Language." Some also refer to it humorously as "Pathologically
Eclectic Rubbish Lister" or "Practically Everything Really Likable."
Evolution of Perl
• Origins: Perl was initially developed to handle tasks involving text le manipulation
and reporting that awk and sed could not ef ciently manage.
• Early Development: The rst version (Perl 1.0) was released in December 1987. It
was written in C and incorporated ideas from awk, sed, and Lisp.
• Growth: Over time, Perl evolved to include features such as regular expressions,
network sockets, and database interactions.
• Current Versions: Perl 5 is the major version in use, with Perl 6 being a
reimplementation focused on object-oriented programming (now known as Raku).
Main Features :
1. Easy to Learn: Its syntax is similar to other high-level languages like C and C++,
making it relatively easy for programmers familiar with these languages.
2. Text Processing: Perl's strong text manipulation capabilities make it ideal for tasks
like generating reports and converting data formats.
3. Feature-Rich: It combines features from various languages (e.g., C, sed, awk),
enhancing its utility.
4. System Administration: Perl simpli es system administration tasks and is used in
web programming, automation, and more.
5. Web Integration: Perl can be embedded in web servers and integrates well with
databases through the DBI (Database Interface) module.
Getting Started with Perl
1. Finding an Interpreter:
◦ You can use online IDEs or install Perl locally. For Windows, options include
Padre and Eclipse with the EPIC plugin.
3. Comments:
30
fi
fi
fi
fi
fi
◦ Multi-Line:
=begin comment
This is a multi-line comment
=cut
4. Print Function:
◦ \n for newline
◦ #!/usr/bin/perl speci es the Perl interpreter
Advantages of Perl
1. Text Processing: Ideal for extracting and analyzing data from text les.
2. CGI Scripts: Commonly used for web server scripting.
3. Web Development: Useful for server-side scripting and web automation.
4. GUI Development: Can be used for creating graphical user interfaces.
5. SQL Query Generation: Handy for constructing and executing SQL queries.
31
fi
fi