SlideShare a Scribd company logo
1 of 74
Download to read offline
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Ruby Introduction
Let us write a simple program in ruby. All ruby files will have extension  .rb . So put the following source code in a test.rb file.  puts "Hello, Ruby!"; Here I assumed that you have ruby interpreter available in /usr/bin directory. Now try to run this program as follows: ruby test.rb This will produce following result: Hello, Ruby!
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Ruby Comments: A comment hides a line, part of a line, or several lines from the Ruby interpreter. You can use the hash character (#) at the beginning of a line: # I am a comment. Just ignore me. Or, a comment may be on the same line after a statement or expression: name = "Madisetti" # This is again comment You can comment multiple lines as follows: # This is a comment. # This is a comment, too. # This is a comment, too. # I said that already.
Here is another form. This block comment conceals several lines from the interpreter with =begin/=end: =begin This is a comment. This is a comment, too. This is a comment, too. I said that already. =end
Ruby Arithmetic Operators: Ruby Operators ,[object Object],[object Object],[object Object],[object Object],[object Object]
Ruby Comparison Operators: <=>   ,[object Object],[object Object],[object Object],[object Object],(a <=> b) returns -1.  Example
[object Object],[object Object],[object Object],[object Object],Ruby Logical Operators: ,[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Ruby Range operators: Sequence ranges in Ruby are used to create a range of successive values - consisting of a start value, an end value and a range of values in between. In Ruby, these sequences are created using the &quot;..&quot; and &quot;...&quot; range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value. Operator Description Example .. Creates a range from start point to end point inclusive 1..10 Creates a range from 1 to 10 inclusive ... Creates a range from start point to end point exclusive 1...10 Creates a range from 1 to 9
[object Object],[object Object],[object Object],defined? variable # True if variable is initialized  ,[object Object],[object Object],[object Object],[object Object],[object Object]
Ruby Parallel Assignment: Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Ruby code. For example: a = 10 b = 20 c = 30 may be more quickly declared using parallel assignment: a, b, c = 10, 20, 30 Parallel assignment is also useful for swapping the values held in two variables: a, b = b, c
Ruby offers contional structures that are pretty common to modern languages. Here we will explain all the  Conditional Statements  and modifiers available in Ruby ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Ruby if modifier: Syntax: code if condition Executes code if the conditional is true. ,[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Loops in Ruby are used to execute the same block of code a specified number of times. This chapter details all the  Loop Statements  supported by Ruby.  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],If retry appears in the iterator, the block, or the body of the for expression, restarts the invocation of the iterator call. Arguments to the iterator is re-evaluated. for i in 1..5 retry if some_condition  # restart from i == 1 end
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Ruby Methods ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],The number of parameters is 3 The parameters are Zara The parameters are 6 The parameters are F The number of parameters is 4 The parameters are Mac The parameters are 36 The parameters are M The parameters are MCA Output
Ruby Blocks ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Variables in a Ruby Class: Ruby provides four types of variables: 1.Local Variables:  Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more detail about method in subsequent chapter. Local variables begin with a lowercase letter or _. 2.Instance Variables:  Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name. 3. Class Variables:  Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name.
4.Global Variables:  Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($).
Ruby Classes & Objects class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts &quot;Customer id #@cust_id&quot; puts &quot;Customer name #@cust_name&quot; puts &quot;Customer address #@cust_addr&quot; end def total_no_of_customers() @@no_of_customers += 1 puts &quot;Total number of customers: #@@no_of_customers&quot; end end # Create Objects cust1=Customer.new(&quot;1&quot;, &quot;John&quot;, &quot;Wisdom Apartments, Ludhiya&quot;) cust2=Customer.new(&quot;2&quot;, &quot;Poul&quot;, &quot;New Empire road, Khandala&quot;) # Call Methods cust1.display_details() cust1.total_no_of_customers() cust2.display_details() cust2.total_no_of_customers()
Output Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya Total number of customers: 1 Customer id 2 Customer name Poul Customer address New Empire road, Khandala Total number of customers: 2
[object Object],[object Object],class Mammal      def breathe        puts &quot;inhale and exhale&quot;      end   end      class Cat < Mammal      def speak        puts &quot;Meow&quot;      end   end      rani = Cat.new   rani.breathe   rani.speak   Inheritance
Features of Ruby ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],A dynamic, open source programming language with a focus on simplicity and productivity ,[object Object]
[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Port numbers work like telephone extensions. Just as a business telephone switchboard can use a main phone number and assign each employee an extension number (like x100, x101, etc.), so a computer has a main address and a set of port numbers to handle incoming and outgoing connections. ,[object Object],[object Object],Internet Addresses ,[object Object]
We shall develop sockets-based networking applications using the Ruby language. Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents. Sockets
Socket Programming Usage of TCP Server  Here we will write a very simple client program which will open a connection to a given port and given host. Ruby class TCPSocket provides open function to open such a socket. The TCPSocket.open(host, port) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file. The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits:
require 'socket'  # Sockets are in standard library host = 'localhost' port = 2000 s = TCPSocket.open(host, port) while line = s.gets  # Read lines from the socket puts line  # And print with platform line terminator end s.close  # Close the socket when done Client:
Server: To write Internet servers, we use the TCPServer class. A TCPServer object is a factory for TCPSocket objects. Now call TCPServer.open(hostname, port function to specify a port for your service and create a TCPServer object. Next, call the accept method of the returned TCPServer object. This method waits until a client connects to the port you specified, and then returns a TCPSocket object that represents the connection to that client.
require 'socket'  # Get sockets from stdlib server = TCPServer.open(2000)  # Socket to listen on port 2000 loop {  # Servers run forever client = server.accept  # Wait for a client to connect client.puts(“welcome”)  # Send the message to client client.puts &quot;Closing the connection. Bye!&quot; client.close  # Disconnect from the client } Now run this server in background and then run above client to see the result.
The Date Time Server and Client Now let us build a Ruby-based Date Time server and client that displays on the client computer the date and time at the server location, using the Ruby socket API. Here's the code for the Date Time Server Here's the code for the Date Time Client require 'socket'  # Get sockets from stdlib server = TCPServer.open(2000)  # Socket to listen on port 2000 loop {  # Servers run forever client = server.accept  # Wait for a client to connect client.puts(Time.now)  # Send the time to the client client.puts &quot;Closing the connection. Bye!&quot; client.close  # Disconnect from the client }
Explanation of the above code: You first load the socket library with the require command. The TCPServer class is a helper class for building TCP socket servers. The TCPServer.new('localhost', 20000) statement creates a new socket identified by localhost and port number. The Thread.start creates and runs a new thread to execute instructions given in block. Any arguments passed to Thread.start are passed into the block. The dts.accept method waits for a connection on dts, and returns a new TCPSocket object connected to the caller. The Kernel.loop iterator calls the associated block do..end) forever (or at least until you break out of the loop). We use s.write(Time.now) to write the current date and time on the server to the socket. Finally, we write s.close to close a socket using the close method. This method is inherited from the IO class, but it's available for each of the socket types.
Here's the code for the Date Time Client  require 'socket'  streamSock = TCPSocket.new( &quot;127.0.0.1&quot;, 20000 )  str = streamSock.recv( 100 )  print str  streamSock.close  You first load the socket library with the require command. The statement sock = TCPSocket.new('127.0.0.1', 20000) opens a TCP connection to localhost on port 20000. The statement str = sock.recv(100) receives up to 100 bytes from sock. We display the date-time string received from the server and finally we close the socket. Explanation of the above code:
Web Services with Ruby The Simple Object Access Protocol (SOAP) is a cross-platform and language-independent RPC protocol based on XML and, usually (but not necessarily) HTTP. It uses XML to encode the information that makes the remote procedure call, and HTTP to transport that information across a network from clients to servers and vice versa. What is SOAP ?
Example require 'soap/wsdlDriver‘ # URL for the service WSDL wsdl = 'http://www.ebi.ac.uk/Tools/webservices/wsdl/WSDbfetch.wsdl' begin # Get the object from the WSDL dbfetchSrv = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver # SOAP message trace output dbfetchSrv.wiredump_dev = STDOUT # Get data from the service puts dbfetchSrv.fetchData(&quot;UNIPROT:ADH1A_HUMAN&quot;, &quot;fasta&quot;, &quot;raw&quot;) end
[object Object],[object Object],SOAP4R: SOAP::WSDLDriverFactory.new().create_rpc_driver can be used to create a service proxy, from a WSDL document, which provides an interface to the web service. Using the methods provided by the service proxy the service can be used as though it was a local resource.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

More Related Content

What's hot

PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScriptRavi Bhadauria
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOMMindy McAdams
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScriptShahDhruv21
 
Regular expression in javascript
Regular expression in javascriptRegular expression in javascript
Regular expression in javascriptToan Nguyen
 
Chapter 02 php basic syntax
Chapter 02   php basic syntaxChapter 02   php basic syntax
Chapter 02 php basic syntaxDhani Ahmad
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingHaim Michael
 

What's hot (20)

Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Clean code
Clean codeClean code
Clean code
 
Java script
Java scriptJava script
Java script
 
Regular expression in javascript
Regular expression in javascriptRegular expression in javascript
Regular expression in javascript
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Chapter 02 php basic syntax
Chapter 02   php basic syntaxChapter 02   php basic syntax
Chapter 02 php basic syntax
 
Laravel Blade Template
Laravel Blade TemplateLaravel Blade Template
Laravel Blade Template
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
Java features
Java featuresJava features
Java features
 
AngularJS
AngularJS AngularJS
AngularJS
 

Viewers also liked

Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to RubyRanjith Siji
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails PresentationJoost Hietbrink
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentationadamcookeuk
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Rubykim.mens
 
Ruby On Rails - Porque Utilizar?
Ruby On Rails - Porque Utilizar?Ruby On Rails - Porque Utilizar?
Ruby On Rails - Porque Utilizar?David Ruiz
 
Welcome to ruby!
Welcome to ruby!Welcome to ruby!
Welcome to ruby!성훈 김
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objectsHarkamal Singh
 
Loops PHP 04
Loops PHP 04Loops PHP 04
Loops PHP 04Spy Seat
 
Память руби изнутри
Память руби изнутриПамять руби изнутри
Память руби изнутриvasfed
 
Programming for the non-programmer
Programming for the non-programmerProgramming for the non-programmer
Programming for the non-programmerStelian Firez
 
Ruby Data Types and Data Structures
Ruby Data Types and Data StructuresRuby Data Types and Data Structures
Ruby Data Types and Data StructuresNola Stowe
 
Ruby On Rails Basics
Ruby On Rails BasicsRuby On Rails Basics
Ruby On Rails BasicsAmit Solanki
 

Viewers also liked (20)

Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Ruby on Rails for beginners
Ruby on Rails for beginnersRuby on Rails for beginners
Ruby on Rails for beginners
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Why Ruby
Why RubyWhy Ruby
Why Ruby
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Ruby
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 
Ruby on Rails small application demo
Ruby on Rails small application demoRuby on Rails small application demo
Ruby on Rails small application demo
 
Programming Basics - array, loops, funcitons
Programming Basics - array, loops, funcitonsProgramming Basics - array, loops, funcitons
Programming Basics - array, loops, funcitons
 
Ruby On Rails - Porque Utilizar?
Ruby On Rails - Porque Utilizar?Ruby On Rails - Porque Utilizar?
Ruby On Rails - Porque Utilizar?
 
Express 4
Express 4Express 4
Express 4
 
Welcome to ruby!
Welcome to ruby!Welcome to ruby!
Welcome to ruby!
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
 
Loops PHP 04
Loops PHP 04Loops PHP 04
Loops PHP 04
 
Ruby on rails porque usar rails?!
Ruby on rails   porque usar rails?!Ruby on rails   porque usar rails?!
Ruby on rails porque usar rails?!
 
Память руби изнутри
Память руби изнутриПамять руби изнутри
Память руби изнутри
 
Programming for the non-programmer
Programming for the non-programmerProgramming for the non-programmer
Programming for the non-programmer
 
PHP vs. Ruby on Rails
PHP vs. Ruby on RailsPHP vs. Ruby on Rails
PHP vs. Ruby on Rails
 
Ruby Data Types and Data Structures
Ruby Data Types and Data StructuresRuby Data Types and Data Structures
Ruby Data Types and Data Structures
 
Ruby On Rails Basics
Ruby On Rails BasicsRuby On Rails Basics
Ruby On Rails Basics
 

Similar to Ruby Basics

Case, Loop & Command line args un Unix
Case, Loop & Command line args un UnixCase, Loop & Command line args un Unix
Case, Loop & Command line args un UnixVpmv
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# DevelopersCory Foy
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technologyppparthpatel123
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
 
Php Loop
Php LoopPhp Loop
Php Looplotlot
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++Neeru Mittal
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kianphelios
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping newaprilyyy
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.gerrell
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfranjanadeore1
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorialadelaticleanu
 
What is the general format for a Try-Catch block Assume that amt l .docx
 What is the general format for a Try-Catch block  Assume that amt l .docx What is the general format for a Try-Catch block  Assume that amt l .docx
What is the general format for a Try-Catch block Assume that amt l .docxajoy21
 

Similar to Ruby Basics (20)

10 ruby loops
10 ruby loops10 ruby loops
10 ruby loops
 
09 ruby if else
09 ruby if else09 ruby if else
09 ruby if else
 
Ruby
RubyRuby
Ruby
 
04 ruby syntax
04 ruby syntax04 ruby syntax
04 ruby syntax
 
Case, Loop & Command line args un Unix
Case, Loop & Command line args un UnixCase, Loop & Command line args un Unix
Case, Loop & Command line args un Unix
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
Php Loop
Php LoopPhp Loop
Php Loop
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
Ruby
RubyRuby
Ruby
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdf
 
My final requirement
My final requirementMy final requirement
My final requirement
 
Ruby Hell Yeah
Ruby Hell YeahRuby Hell Yeah
Ruby Hell Yeah
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
 
What is the general format for a Try-Catch block Assume that amt l .docx
 What is the general format for a Try-Catch block  Assume that amt l .docx What is the general format for a Try-Catch block  Assume that amt l .docx
What is the general format for a Try-Catch block Assume that amt l .docx
 

More from SHC

Perform brute force
Perform brute forcePerform brute force
Perform brute forceSHC
 
AJAX ASP.Net
AJAX ASP.NetAJAX ASP.Net
AJAX ASP.NetSHC
 
C++ plus data structures, 3rd edition (2003)
C++ plus data structures, 3rd edition (2003)C++ plus data structures, 3rd edition (2003)
C++ plus data structures, 3rd edition (2003)SHC
 
Inside Asp.Net Web Matrix
Inside Asp.Net Web MatrixInside Asp.Net Web Matrix
Inside Asp.Net Web MatrixSHC
 
V Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedV Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedSHC
 
V Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedV Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedSHC
 
V Pro Bp08505 Phase Ii Edited
V Pro Bp08505 Phase Ii EditedV Pro Bp08505 Phase Ii Edited
V Pro Bp08505 Phase Ii EditedSHC
 
Intel® V Pro™ Technology
Intel® V Pro™ TechnologyIntel® V Pro™ Technology
Intel® V Pro™ TechnologySHC
 
XForms with Linux
XForms with LinuxXForms with Linux
XForms with LinuxSHC
 
XForms
XFormsXForms
XFormsSHC
 
Rails
RailsRails
RailsSHC
 
Call
CallCall
CallSHC
 
Action Mailer
Action MailerAction Mailer
Action MailerSHC
 
Ruby Security
Ruby SecurityRuby Security
Ruby SecuritySHC
 
Web Services
Web ServicesWeb Services
Web ServicesSHC
 
Pragmatic Agile Web Development With Rails.3rd Edition.2009
Pragmatic   Agile Web Development With Rails.3rd Edition.2009Pragmatic   Agile Web Development With Rails.3rd Edition.2009
Pragmatic Agile Web Development With Rails.3rd Edition.2009SHC
 
Ruby Installation
Ruby InstallationRuby Installation
Ruby InstallationSHC
 
Mysql Statments
Mysql StatmentsMysql Statments
Mysql StatmentsSHC
 
Mysql Fun
Mysql FunMysql Fun
Mysql FunSHC
 
Mysql
MysqlMysql
MysqlSHC
 

More from SHC (20)

Perform brute force
Perform brute forcePerform brute force
Perform brute force
 
AJAX ASP.Net
AJAX ASP.NetAJAX ASP.Net
AJAX ASP.Net
 
C++ plus data structures, 3rd edition (2003)
C++ plus data structures, 3rd edition (2003)C++ plus data structures, 3rd edition (2003)
C++ plus data structures, 3rd edition (2003)
 
Inside Asp.Net Web Matrix
Inside Asp.Net Web MatrixInside Asp.Net Web Matrix
Inside Asp.Net Web Matrix
 
V Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedV Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii Edited
 
V Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedV Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii Edited
 
V Pro Bp08505 Phase Ii Edited
V Pro Bp08505 Phase Ii EditedV Pro Bp08505 Phase Ii Edited
V Pro Bp08505 Phase Ii Edited
 
Intel® V Pro™ Technology
Intel® V Pro™ TechnologyIntel® V Pro™ Technology
Intel® V Pro™ Technology
 
XForms with Linux
XForms with LinuxXForms with Linux
XForms with Linux
 
XForms
XFormsXForms
XForms
 
Rails
RailsRails
Rails
 
Call
CallCall
Call
 
Action Mailer
Action MailerAction Mailer
Action Mailer
 
Ruby Security
Ruby SecurityRuby Security
Ruby Security
 
Web Services
Web ServicesWeb Services
Web Services
 
Pragmatic Agile Web Development With Rails.3rd Edition.2009
Pragmatic   Agile Web Development With Rails.3rd Edition.2009Pragmatic   Agile Web Development With Rails.3rd Edition.2009
Pragmatic Agile Web Development With Rails.3rd Edition.2009
 
Ruby Installation
Ruby InstallationRuby Installation
Ruby Installation
 
Mysql Statments
Mysql StatmentsMysql Statments
Mysql Statments
 
Mysql Fun
Mysql FunMysql Fun
Mysql Fun
 
Mysql
MysqlMysql
Mysql
 

Recently uploaded

Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Nikki Chapple
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sectoritnewsafrica
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...itnewsafrica
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 

Recently uploaded (20)

Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
Microsoft 365 Copilot: How to boost your productivity with AI – Part two: Dat...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
Irene Moetsana-Moeng: Stakeholders in Cybersecurity: Collaborative Defence fo...
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 

Ruby Basics

  • 1.
  • 2. Let us write a simple program in ruby. All ruby files will have extension .rb . So put the following source code in a test.rb file. puts &quot;Hello, Ruby!&quot;; Here I assumed that you have ruby interpreter available in /usr/bin directory. Now try to run this program as follows: ruby test.rb This will produce following result: Hello, Ruby!
  • 3.
  • 4.
  • 5.
  • 6. Ruby Comments: A comment hides a line, part of a line, or several lines from the Ruby interpreter. You can use the hash character (#) at the beginning of a line: # I am a comment. Just ignore me. Or, a comment may be on the same line after a statement or expression: name = &quot;Madisetti&quot; # This is again comment You can comment multiple lines as follows: # This is a comment. # This is a comment, too. # This is a comment, too. # I said that already.
  • 7. Here is another form. This block comment conceals several lines from the interpreter with =begin/=end: =begin This is a comment. This is a comment, too. This is a comment, too. I said that already. =end
  • 8.
  • 9.
  • 10.
  • 11.
  • 12. Ruby Range operators: Sequence ranges in Ruby are used to create a range of successive values - consisting of a start value, an end value and a range of values in between. In Ruby, these sequences are created using the &quot;..&quot; and &quot;...&quot; range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value. Operator Description Example .. Creates a range from start point to end point inclusive 1..10 Creates a range from 1 to 10 inclusive ... Creates a range from start point to end point exclusive 1...10 Creates a range from 1 to 9
  • 13.
  • 14. Ruby Parallel Assignment: Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Ruby code. For example: a = 10 b = 20 c = 30 may be more quickly declared using parallel assignment: a, b, c = 10, 20, 30 Parallel assignment is also useful for swapping the values held in two variables: a, b = b, c
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53. Variables in a Ruby Class: Ruby provides four types of variables: 1.Local Variables: Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more detail about method in subsequent chapter. Local variables begin with a lowercase letter or _. 2.Instance Variables: Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name. 3. Class Variables: Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name.
  • 54. 4.Global Variables: Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($).
  • 55. Ruby Classes & Objects class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts &quot;Customer id #@cust_id&quot; puts &quot;Customer name #@cust_name&quot; puts &quot;Customer address #@cust_addr&quot; end def total_no_of_customers() @@no_of_customers += 1 puts &quot;Total number of customers: #@@no_of_customers&quot; end end # Create Objects cust1=Customer.new(&quot;1&quot;, &quot;John&quot;, &quot;Wisdom Apartments, Ludhiya&quot;) cust2=Customer.new(&quot;2&quot;, &quot;Poul&quot;, &quot;New Empire road, Khandala&quot;) # Call Methods cust1.display_details() cust1.total_no_of_customers() cust2.display_details() cust2.total_no_of_customers()
  • 56. Output Customer id 1 Customer name John Customer address Wisdom Apartments, Ludhiya Total number of customers: 1 Customer id 2 Customer name Poul Customer address New Empire road, Khandala Total number of customers: 2
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63. We shall develop sockets-based networking applications using the Ruby language. Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents. Sockets
  • 64. Socket Programming Usage of TCP Server Here we will write a very simple client program which will open a connection to a given port and given host. Ruby class TCPSocket provides open function to open such a socket. The TCPSocket.open(host, port) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file. The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits:
  • 65. require 'socket' # Sockets are in standard library host = 'localhost' port = 2000 s = TCPSocket.open(host, port) while line = s.gets # Read lines from the socket puts line # And print with platform line terminator end s.close # Close the socket when done Client:
  • 66. Server: To write Internet servers, we use the TCPServer class. A TCPServer object is a factory for TCPSocket objects. Now call TCPServer.open(hostname, port function to specify a port for your service and create a TCPServer object. Next, call the accept method of the returned TCPServer object. This method waits until a client connects to the port you specified, and then returns a TCPSocket object that represents the connection to that client.
  • 67. require 'socket' # Get sockets from stdlib server = TCPServer.open(2000) # Socket to listen on port 2000 loop { # Servers run forever client = server.accept # Wait for a client to connect client.puts(“welcome”) # Send the message to client client.puts &quot;Closing the connection. Bye!&quot; client.close # Disconnect from the client } Now run this server in background and then run above client to see the result.
  • 68. The Date Time Server and Client Now let us build a Ruby-based Date Time server and client that displays on the client computer the date and time at the server location, using the Ruby socket API. Here's the code for the Date Time Server Here's the code for the Date Time Client require 'socket' # Get sockets from stdlib server = TCPServer.open(2000) # Socket to listen on port 2000 loop { # Servers run forever client = server.accept # Wait for a client to connect client.puts(Time.now) # Send the time to the client client.puts &quot;Closing the connection. Bye!&quot; client.close # Disconnect from the client }
  • 69. Explanation of the above code: You first load the socket library with the require command. The TCPServer class is a helper class for building TCP socket servers. The TCPServer.new('localhost', 20000) statement creates a new socket identified by localhost and port number. The Thread.start creates and runs a new thread to execute instructions given in block. Any arguments passed to Thread.start are passed into the block. The dts.accept method waits for a connection on dts, and returns a new TCPSocket object connected to the caller. The Kernel.loop iterator calls the associated block do..end) forever (or at least until you break out of the loop). We use s.write(Time.now) to write the current date and time on the server to the socket. Finally, we write s.close to close a socket using the close method. This method is inherited from the IO class, but it's available for each of the socket types.
  • 70. Here's the code for the Date Time Client require 'socket' streamSock = TCPSocket.new( &quot;127.0.0.1&quot;, 20000 ) str = streamSock.recv( 100 ) print str streamSock.close You first load the socket library with the require command. The statement sock = TCPSocket.new('127.0.0.1', 20000) opens a TCP connection to localhost on port 20000. The statement str = sock.recv(100) receives up to 100 bytes from sock. We display the date-time string received from the server and finally we close the socket. Explanation of the above code:
  • 71. Web Services with Ruby The Simple Object Access Protocol (SOAP) is a cross-platform and language-independent RPC protocol based on XML and, usually (but not necessarily) HTTP. It uses XML to encode the information that makes the remote procedure call, and HTTP to transport that information across a network from clients to servers and vice versa. What is SOAP ?
  • 72. Example require 'soap/wsdlDriver‘ # URL for the service WSDL wsdl = 'http://www.ebi.ac.uk/Tools/webservices/wsdl/WSDbfetch.wsdl' begin # Get the object from the WSDL dbfetchSrv = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver # SOAP message trace output dbfetchSrv.wiredump_dev = STDOUT # Get data from the service puts dbfetchSrv.fetchData(&quot;UNIPROT:ADH1A_HUMAN&quot;, &quot;fasta&quot;, &quot;raw&quot;) end
  • 73.
  • 74.