[go: up one dir, main page]

0% found this document useful (0 votes)
25 views31 pages

SL Imps 1,2,3

scripting languages

Uploaded by

manzar01012003
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)
25 views31 pages

SL Imps 1,2,3

scripting languages

Uploaded by

manzar01012003
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/ 31

UNIT I: Introduction to Ruby

Q.What is Ruby ? Structure and Execution ?


Ruby is a dynamic, object-oriented programming language designed for simplicity and
productivity. It was created by Yukihiro Matsumoto and rst released in 1995. Ruby
emphasizes a clean and readable syntax, making it a popular choice for both beginners and
experienced developers.

Features of Ruby

1. Object-Oriented: Everything in Ruby is an object, including primitive data types like


numbers and strings. This allows for a consistent and powerful object-oriented
programming experience.

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.

4. Flexibility: Ruby allows for extensive metaprogramming, enabling developers to alter


and de ne new methods and classes at runtime.

5. Readability: Ruby’s syntax is designed to be intuitive and easy to read, often


described as being close to natural language.

6. Convention over Con guration: Ruby’s frameworks, particularly Ruby on Rails,


follow the principle of convention over con guration, minimizing the need for
explicit con guration.

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.

Structure and Execution of Ruby

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.

◦ Keywords: Reserved words in Ruby with special meaning, like class,


def, if, while.
◦ Operators: Symbols that perform operations, such as +, -, *, /.
◦ Literals: Values like strings "Hello", numbers 123, and booleans true
or false.
◦ Identi ers: Names for variables, methods, classes, etc., like my_var,
calculate_sum.
2. Whitespace and Comments:

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

Key Syntactic Structures:

1. Expressions:
◦ Arithmetic: a + b, 3 * 5
◦ Logical: x && y, !flag
2. Statements:

◦ Assignment: variable = value


◦ Control Flow: if, while, caseruby

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")

4. Classes and Modules:


◦ Class De nition: Used to create new data types.

class Person
◦ def initialize(name)
◦ @name = name
◦ end

◦ def say_hello
◦ "Hello, #{@name}"
◦ end
◦ end

5. Methods and Functions:


◦ Method De nition: De nes a reusable block of code.

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:

◦ The Ruby interpreter executes the code line by line or instruction by


instruction. It evaluates expressions, executes statements, and invokes
methods.
4. Object Creation:

◦ Ruby is object-oriented, so classes and objects are created and managed


dynamically. For example, when you create a new instance of a class, Ruby
allocates memory and initializes the object.
5. Memory Management:

◦ Garbage Collection: Ruby automatically manages memory through garbage


collection, which cleans up unused objects and frees memory.
6. Exception Handling:

◦ Error Management: Ruby uses begin-rescue-ensure blocks to


handle exceptions and ensure that resources are properly released, even in the
event of an error.

Q.Package management with RubyGems


RubyGems is the package management framework for Ruby that provides a way to
distribute, manage, and install libraries (gems). Each gem can contain code, documentation,
and dependencies necessary for a Ruby project.

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:

• De nition: A gem is a packaged Ruby application or library.


• Structure: A gem typically includes:
◦ Code: The Ruby code for the gem.

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

• Install a Gem: To install a gem, use:

gem install gem_name

For example, to install the rails gem:

gem install rails

• Update a Gem: To update a speci c gem to the latest version:

gem update gem_name

To update all installed gems:

gem update

• Uninstall a Gem: To remove a gem:

gem uninstall gem_name

• List Installed Gems: To see which gems are installed:

gem list

5
fi
fi
fi
• Search for Gems: To search for a gem by name or keyword:

gem search 'keyword'

3. Gem le and Bundler

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'

• gem 'rails', '~> 7.0'


• gem 'pg', '~> 1.2'

• Bundler: To install the gems listed in the Gemfile, you use Bundler. First, install
Bundler if you haven’t already:

gem install bundler


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:

bundle exec rails server

4. Gem Speci cations and Versions

• 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

• Speci c Version: Install a speci c version of a gem:

gem install gem_name -v 'x.y.z'

5. Creating Your Own Gem

If you want to create your own gem, you can use the bundler command to generate the
necessary les:

bundle gem my_gem

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:

• First, build the gem:


gem build my_gem.gemspec

• Then, push it:


gem push my_gem-0.1.0.gem

Make sure to sign up for a RubyGems.org account and con gure your credentials on your
local machine before pushing gems.

Q.What is CGI scripts and explain Writing CGI scripts in Ruby


language

CGI Script:

CGI (Common Gateway Interface) is a standard protocol for interfacing external


applications with web servers. CGI scripts are used to generate dynamic content on websites
by allowing web servers to run scripts or programs in response to client requests. These
scripts can process form data, interact with databases, and generate custom content before
sending it back to the client.

Key Points about CGI:

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

Ruby provides a built-in library for writing CGI scripts.

1. Setting Up the Environment

• 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

A basic Ruby CGI script demonstrates how to generate static content.

Example Script (Hello World):

1. Create a le named hello.rb:

#!/usr/bin/env ruby

require 'cgi'

cgi = CGI.new

print "Content-Type: text/html\n\n"


print "<html><body>"
print "<h1>Hello, World!</h1>"
print “</body></html>"

3. Handling Form Data

CGI scripts can handle data sent from HTML forms.

Example Script (Form Handling):

Create a le named form_handler.rb:

#!/usr/bin/env ruby

8
fi
fi
fi
fi
require 'cgi'

cgi = CGI.new
name = cgi['name'] # Retrieves 'name' parameter from
form data

print "Content-Type: text/html\n\n"


print "<html><body>"
print "<h1>Hello, #{CGI.escapeHTML(name)}!</h1>" unless
name.empty?
print "<p><a href='form.html'>Go back</a></p>"
print "</body></html>"

4. Working with Cookies

Cookies are used to store user-speci c data across requests.

Example Script (Setting and Reading Cookies):

Create a le named cookie_example.rb:

#!/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: '/')

print "Content-Type: text/html\n"


print "Set-Cookie: #{cookie.to_s}\n\n"
print "<html><body>"
print "<h1>Welcome, #{CGI.escapeHTML(name)}!</h1>"
print "</body></html>"

5. Testing and Debugging

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.

Q.What is a cookie? Write the code in Ruby to demonstrate


handling of cookies.
Cookies:

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.

Key Aspects of Cookies:

• Name and Value: Identi es and stores data.


• Path and Domain: De nes the scope of where the cookie is valid.
• Expires/Max-Age: Speci es when the cookie should expire.
• Secure: Ensures the cookie is only sent over HTTPS connections.
• HttpOnly: Prevents access to the cookie via JavaScript for security reasons.

Ruby CGI Handles Cookies

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

Example: Creating a Cookie Object and Storing Text

Script:

#!/usr/bin/env ruby

require 'cgi'

cgi = CGI.new

# Create a cookie named 'my_cookie' with text

10
fi
fi
fi
cookie = CGI::Cookie.new(

name: 'my_cookie',

value: 'This is some text.',

path: '/',

expires: Time.now + 60*60*24*7 # Expires in 7 days

print "Content-Type: text/html\n"

print "Set-Cookie: #{cookie.to_s}\n\n"

print "<html><body><h1>Cookie set!</h1></body></html>"

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:

◦ cookie = CGI::Cookie.new(...): Creates a cookie named


'my_cookie' with the value 'This is some text.', which will
expire in 7 days.
3. Send Cookie to Browser:

◦ print "Set-Cookie: #{cookie.to_s}\n\n": Sends the


cookie to the user’s browser.
4. Display Message:

◦ print "<html><body><h1>Cookie set!</h1></body></


html>": Shows a simple message on the web page saying "Cookie set!"
This script sets a cookie in the user's browser and con rms that the cookie has been set with a
web page message.

Q.SOAP and Webservices ? SOAP4R ?

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.

2. SOAP (Simple Object Access Protocol)

• De nition: SOAP is a protocol for sending structured information between web


services using XML (a format for encoding data). It’s designed for complex and
secure interactions.
Working:

• 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

2. Install SOAP4R Gem: Install the SOAP4R library using


RubyGems. Open your terminal and run:

gem install soap4r

Writing a SOAP4R Server

Here’s a simple example to create a SOAP server using SOAP4R. This server provides a
service that returns a greeting message.

1. Create a SOAP Server:

Create a Ruby script le, e.g., soap_server.rb.

12
fi
fi
fi
require 'soap/rpc/standaloneServer'

# Define a module to implement the SOAP service


module GreetingService
def self.greet(name)
"Hello, #{name}!"
end
end

# Create a SOAP server


server =
SOAP::RPC::StandaloneServer.new('GreetingService',
'urn:GreetingService', 'http://localhost:8080')

# Add the module to the server


server.add_method(GreetingService, 'greet')

# Start the server


server.start

Q.what is RubyTk and explain Creating simple Tk applications


What is RubyTk?

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.

Creating Simple Tk Applications in Ruby

Here’s a step-by-step guide to creating simple Tk applications in Ruby:

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

Creating a basic Tk application with a window that has a button:

Create a le named simple_tk_app.rb:

require 'tk'

13
fi
fi
# Create the main window
root = TkRoot.new { title "Simple Tk App" }

# Create a button widget


button = TkButton.new(root) do
text "Click Me"
command proc { puts "Button clicked!" }
pack
end

# Start the Tk event loop


Tk.mainloop

Explanation:

• require 'tk': Loads the Tk library.


• TkRoot.new { title "Simple Tk App" }: Creates the main window
with the title "Simple Tk App".
• TkButton.new(root): Creates a button widget inside the main window.
◦ text "Click Me": Sets the button label.
◦ command proc { puts "Button clicked!" }: De nes a
procedure that runs when the button is clicked (prints a message to the
console).
◦ pack: Adds the button to the window and manages its layout.
• Tk.mainloop: Starts the Tk event loop to handle user interactions.

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:

• Framework: Rails is a framework that provides a set of conventions and tools to


build web applications.
• Language: It is built using the Ruby programming language, known for its simplicity
and readability.
• Convention over Con guration: Rails emphasizes convention, reducing the number
of decisions developers need to make. This speeds up development and helps
maintain consistency.
Ruby on Rails (Rails) is a web application framework written in Ruby. It simpli es building
web apps with its set of conventions and tools.

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

1. Rapid Development: Fast to build applications.


2. Less Con guration: Follows conventions to minimize setup.
3. Strong Community: Lots of support and resources.
4. Integrated Testing: Built-in tools for testing code.
5. Rich Ecosystem: Many available libraries (gems).

Cons

1. Performance: Can be slower compared to some frameworks.


2. Learning Curve: Can be complex for beginners.
3. Memory Usage: Rails applications can use a lot of memory.
4. Rigid Conventions: Less exibility for unconventional needs.
5. Frequent Updates: New versions can cause compatibility issues.

UNIT II: Extending Ruby

Q.Explain Memory Allocation in Ruby

Memory Allocation in Ruby Extensions

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.

Key Memory Allocation Routines

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);

Memory Allocation in Ruby

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

◦ Description: Manages memory at runtime using a stack structure. Memory is


allocated and deallocated as functions are called and return.
◦ Use Case: Local variables within functions.
3. Heap Allocation:

◦ Description: Allocates and deallocates memory dynamically from a large pool


known as the heap. This allows for exible memory management at runtime.
◦ Use Case: Dynamically sized data structures like arrays and objects.
Steps to Find a Memory Leak in Ruby

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.

Q.Explain Ruby Type Systems

Ruby Type System

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

1. Dynamic Typing vs. Static Typing:

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

◦ De nition: A programming style where an object is considered valid if it


responds to a required set of methods, regardless of its actual class or type.
◦ Bene t: Flexibility and ease of use, without requiring explicit type
declarations or inheritance.
◦ Issue: Assumptions about method availability can be hidden, making code
harder to understand and debug.
3. RBS (Ruby Signature):

◦ De nition: A new language introduced in Ruby 3 for type signatures, written


in .rbs les. It provides a way to de ne types separately from Ruby code.
◦ Purpose: Allows for optional type checking without changing existing Ruby
code. It is similar to TypeScript's .d.ts les or C/C++'s .h les.
◦ Bene t: Helps catch type errors and improves code understanding while
keeping existing codebases intact.
4. Interface Types:

◦ De nition: Represents a set of methods that an object must respond to,


independent of the concrete class or module.
◦ Example: Interface_Appendable requires the << operator for
appending strings. Methods accepting _Appendable can work with any
object implementing the required methods, enhancing the exibility and
readability of code.

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

1. Finding More Bugs:


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.

Q.Explain the Concept of Embedding Ruby

Embedding Ruby in Other Languages

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

◦ Ease of Development: Some complex systems are easier to implement in a


high-level language like Ruby due to its rich libraries and simpler syntax.
◦ Rapid Prototyping: Develop prototypes quickly in Ruby, while relying on
lower-level languages for performance-critical components.

Methods for Embedding Ruby

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
}

// De ne the Ruby method


void Init_my_extension() {
VALUE klass = rb_de ne_class("MyClass", rb_cObject);
rb_de ne_method(klass, "fast_method", fast_method, 0);
}

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.

# Example of using a Java class in JRuby


java_import 'java.util.ArrayList'

list = ArrayList.new
list.add("Hello")
puts list.get(0) # Outputs "Hello"

Q.Explain Embedding a Interpreter with Ruby

Embedding a Ruby Interpreter

• 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();

/* Set the script name */


ruby_script("embedded");

/* Load a Ruby le */
rb_load_ le("start.rb");

/* Main loop of the application */


while (1) {
if (need_to_do_ruby) {
/* Run Ruby code */
ruby_run();
}
}
return 0;
}

Key API Functions

20
fi
fi
fi
1. ruby_init()

◦ Purpose: Initializes the Ruby interpreter.


◦ Usage: Must be called before using any other Ruby-related functions.
2. ruby_options(int argc, char **argv)

◦ Purpose: Passes command-line options to the Ruby interpreter.


◦ Usage: Call this to set options similar to those passed to Ruby from the
command line.
3. ruby_script(char *name)

◦ 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: Loads and executes a Ruby script le.


◦ Usage: Use this to run Ruby code from a le.
5. ruby_run()

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

UNIT III: Introduction to PERL and Scripting

Q.What are scripting languages ? Origin and characteristics of


scripting languages
Scripting Languages:

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.

Origins of Scripting Languages

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

1. Interpreted: Code is executed directly by an interpreter, without a separate


compilation step.
2. Easy to Write: Features simple, readable syntax designed for quick development.
3. Rapid Development: Supports fast coding and iteration, ideal for prototyping and
automation.
4. Dynamic Typing: Variables do not need explicit type declarations; their type is
determined at runtime.
5. High-Level Abstractions: Provides easy-to-use constructs for tasks like le handling
and data manipulation.
6. Automation: Often used to automate repetitive tasks and control software or systems.
7. Integration: Facilitates interaction with other programs, software, or systems.
8. Flexibility: Versatile and applicable to a wide range of tasks, including web
development, system administration, and data analysis.
9. Garbage Collection: Many include automatic memory management to handle
memory ef ciently.
10. Extensibility: Supports libraries and modules, allowing users to extend functionality
and integrate with various tools and systems.
Examples

• Bash/Shell Script: Used for automating tasks in Unix/Linux systems.


• Perl: Known for text manipulation and system administration.
• Python: Popular for its simplicity and broad application in web development,
automation, and data science.
• JavaScript: Enhances web pages with interactive features.
• Ruby: Valued for its clean syntax and use in web development, especially with Ruby
on Rails.

Q.Explain Uses of Scripting Languages

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.

Uses for Scripting Languages

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.

Modern Applications of Scripting Languages

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:

◦ Purpose: Control scriptable objects and integrate with applications.


◦ Examples: Microsoft Visual Basic and Excel's scriptable objects, enabling
automation and customization.
3. Web Scripting:

◦ Purpose: Dynamic web content generation and processing.


◦ Forms:
▪ Processing Forms: Handle user inputs and data.
▪ Dynamic Web Pages: Create interactive and responsive pages.
▪ Dynamically Generating HTML: Generate HTML content on-the- y.
Traditional Applications of Scripting Languages

1. System Administration:
◦ Purpose: Automate administrative tasks and manage systems.
◦ Examples: Shell scripting for task automation and system con guration.
2. Experimental Programming:

◦ Purpose: Develop and test new ideas quickly.


◦ Examples: Prototyping and scripting for experimental code.
3. Controlling Applications:

◦ Purpose: Control and extend application functionality.


◦ Examples: Custom scripts to manage application behavior and interactions.
Application Areas

1. Command Scripting Languages:


◦ Purpose: Control tasks and programs.
◦ Examples: JCL (Job Control Language), Unix shell scripts, text-processing
languages like sed and awk.
2. Application Scripting Languages:

◦ Purpose: Extend and automate applications.


◦ Examples: Visual Basic, Visual Basic for Applications (VBA) for of ce
automation.
3. Markup Languages:

◦ Purpose: Format and transform text documents.


◦ Examples: SGML (Standard Generalized Markup Language), HTML
(HyperText Markup Language), XML (eXtensible Markup Language).
4. Universal Scripting Languages:

◦ Purpose: General-purpose scripting and automation.


◦ Examples:
▪ Perl: Known for report generation and web scripting.

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.

Q.Explain Web Scripting


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

b. Dynamic Web Pages

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.

c. Dynamically Generated HTML

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 and Values

• 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

Perl uses different types of variables, each represented by a special symbol:

1. Scalar Variables ($):

◦ Represent single values (numbers, strings).


◦ Example: $age = 25; (where $age holds the number 25).
2. Array Variables (@):

◦ Represent lists of values.


◦ Example: @colors = ('red', 'green', 'blue'); (where
@colors holds a list of color names).
3. Hash Variables (%):

◦ Represent key-value pairs (dictionaries).


◦ Example: %person = ('name' => 'Alice', 'age' =>
30); (where %person holds a mapping of keys to values).
Scalar Expressions

Scalar expressions are operations that work with scalar values (single values). Some
examples include:

• Arithmetic Operations: Performing calculations with numbers.

◦ Example: $sum = 5 + 10; (where $sum will be 15).


• String Operations: Manipulating strings.

25
fi
fi
◦ Example: $greeting = "Hello" . " World"; (where
$greeting will be "Hello World").
• Comparison Operations: Comparing scalar values.

◦ Example: $is_equal = ($x == $y); (where $is_equal will be


true if $x and $y are equal).
• Assignment: Assigning values to variables.

◦ Example: $number = 42; (where $number is assigned the value 42).

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

Q.Control structures, arrays, lists, hashes, strings, pattern


matching, and regular expressions

control structures, arrays, lists, hashes, strings, pattern matching, and regular expressions in
Perl:

Control Structures

Control structures in Perl manage the ow of execution in a program. They include:

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);

3. last and next:

last: Exits from the loop


last;

next: Skips the rest of the current loop iteration and moves to the next
iteration.
next;

Arrays and Lists

1. Arrays:

◦ Arrays in Perl are ordered lists of scalars.

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:

@list = (1, 2, 3, 4);

Hashes

1. Hashes:
◦ Hashes are unordered collections of key-value pairs.

Declaration and Initialization:


%person = ('name' => 'Alice', 'age' => 30);
Accessing Values:
$name = $person{'name'}; # 'Alice'
Hash Operations:
$person{'city'} = 'New York'; # Adds a new key-
value pair
delete $person{'age'}; # Removes the key 'age'

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:

◦ Perl uses regular expressions for pattern matching.


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

$string =~ /regex/; # Checks if the regex matches the string


$string =~ s/old/new/; # Replaces 'old' with 'new'
$matches = $string =~ /(pattern)/; # Captures the match in $1

◦ 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

Q.Explain PERL programming language

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 :

Perl is popular for several reasons:

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.

2. Writing a Simple Perl Program:

◦ Programs are typically saved with the .pl or .PL extension.


Example Program:
#!/usr/bin/perl
# Print a simple message
print "Welcome to CSE DEPT!\n";

◦ To run the program, use the command: perl le_name.pl

3. Comments:

◦ Single Line: # This is a comment

30
fi
fi
fi
fi
fi
◦ Multi-Line:

=begin comment
This is a multi-line comment
=cut

4. Print Function:

◦ Outputs text to the console: print "Text to display\n";


5. Quotes:

◦ Single Quotes: No interpolation ('text')


◦ Double Quotes: Interpolation enabled ("text $variable")
6. Special Characters:

◦ \n for newline
◦ #!/usr/bin/perl speci es the Perl interpreter
Advantages of Perl

1. Cross-Platform: Compatible with various operating systems and markup languages


like HTML and XML.
2. Text Manipulation: Excellent for handling and processing text with regular
expressions.
3. Free and Open Source: Licensed under Artistic License and GPL.
4. Embeddable: Can be embedded in web and database servers.
5. CPAN Modules: Access to over 25,000 modules for extended functionality (e.g.,
XML processing, GUI, database integration).
Disadvantages of Perl

1. Portability Issues: Some modules on CPAN may affect portability.


2. Performance: Slower execution compared to compiled languages due to
interpretation.
3. Code Readability: Multiple ways to achieve the same result can lead to messy code.
4. Usability: May be less user-friendly compared to other modern languages.
Applications 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

You might also like