SlideShare a Scribd company logo
Ruby was introduced by Yukihiro Matsumoto (known widely as  “Matz”) Ruby originated in Japan during the mid-1990s  Ruby is Based on Perl,Smalltalk,Eiffel,Ada and Lisp. Ruby offers automatic memory management. Ruby is Written in c Ruby is a dynamic interpreted language which has many  strong features of various languages. It is a strong Object oriented programming language.  Ruby is open source Ruby can be embeded into Hypertext Markup Language (HTML). Ruby has similar syntax to that of many programming languages such as C++ and Perl.  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!
Ruby BEGIN Statement Syntax: BEGIN { code } Declares code to be called before the program is run. Example: puts "This is main Ruby Program" BEGIN { puts "Initializing Ruby Program" } This will produce following result: Initializing Ruby Program This is main Ruby Program
Ruby END Statement Syntax: END { code } Declares code to be called at the end of the program.
Example: puts "This is main Ruby Program" END { puts "Terminating Ruby Program" } BEGIN { puts "Initializing Ruby Program" } This will produce following result: Initializing Ruby Program This is main Ruby Program Terminating Ruby Program
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 ** Exponent - Performs exponential (power) calculation on operators a**b will give 10 to the power 20 Example 2**3=>8
Ruby Comparison Operators: <=>   Combined comparison operator.  Return 0 if first operand equals second Return 1 if first operand is greater than the second. Return -1 if first operand is less than the second. (a <=> b) returns -1.  Example
eql? True if the receiver and argument have both the same type and equal values. Example 1 == 1.0 returns true, but 1.eql?(1.0) is false. Ruby Logical Operators: and   Called Logical AND operator. If both the operands are true then then condition becomes true. Example (a and b) is true.
or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. Example (a or b) is true. not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.   Example not(a && b) is false.
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
Ruby defined? operators: defined? is a special operator that takes the form of a method call to determine whether or not the passed expression is defined. It returns a description string of the expression, or  nil  if the expression isn't defined. There are various usage of defined? operator: defined? variable # True if variable is initialized  Example foo = 42 defined? foo  # => &quot;local-variable&quot; defined? $_  # => &quot;global-variable&quot; defined? bar  # => nil (undefined)
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 Ruby if...else Statement: Syntax: if conditional [then]   code... [elsif conditional [then]   code...]... [else   code...] end
if  expressions are used for conditional execution. The values  false  and  nil  are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif. Executes  code  if the  conditional  is true. If the  conditional  is not true,  code  specified in the else clause is executed. An if expression's  conditional  is separated from code by the reserved word  then , a newline, or a semicolon.
Example: x=1 if x > 2 puts &quot;x is greater than 2&quot; elsif x <= 2 and x!=0 puts &quot;x is 1&quot; else puts &quot;I can't guess the number&quot; end Output x is 1
Ruby if modifier: Syntax: code if condition Executes code if the conditional is true. Example: $debug=1 print  &quot;debug\n&quot; if $debug Output: debug
Ruby unless Statement: Syntax: unless conditional [then] code [else code ] end Executes code if conditional is false. If the conditional is true, code specified in the else clause is executed.
Example: x=1 unless x>2 puts &quot;x is less than 2&quot; else puts &quot;x is greater than 2&quot; end This will produce following result: x is less than 2
Ruby unless modifier: Syntax: code unless conditional Executes code if conditional is false. Example: $var =  1 print &quot;1 -- Value is set\n&quot; if $var print &quot;2 -- Value is set\n&quot; unless $var $var = false print &quot;3 -- Value is set\n&quot; unless $var This will produce following result: 1 -- Value is set 3 -- Value is set
Ruby case Statement Syntax: case expression [when expression [, expression ...] [then] code ]... [else code ] end Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches. The expression specified by the when clause is evaluated as the left operand. If no when clauses match, case executes the code of the else clause. A when statement's expression is separated from code by the reserved word then, a newline, or a semicolon.
Example: $age =  5 case $age when 0 .. 2 puts &quot;baby&quot; when 3 .. 6 puts &quot;little child&quot; when 7 .. 12 puts &quot;child&quot; when 13 .. 18 puts &quot;youth&quot; else puts &quot;adult&quot; end This will produce following result: little child
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.  Ruby while Statement: Syntax: while conditional [do] code end Executes code while conditional is true. A while loop's conditional is separated from code by the reserved word do, a newline, backslash \, or a semicolon ;.
Example: $i = 0; $num = 5; while $i < $num  do puts(&quot;Inside the loop i = #$i&quot; ); $i +=1; end This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4
Ruby while modifier: Syntax: code while condition OR begin  code  end while conditional Executes code while conditional is true. If a while modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated.
Example: $i = 0; $num = 5; begin puts(&quot;Inside the loop i = #$i&quot; ); $i +=1; end while $i < $num This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4
Ruby until Statement: Syntax: until conditional [do] code end Executes code while conditional is false. An until statement's conditional is separated from code by the reserved word do, a newline, or a semicolon.
Example: $i = 0; $num = 5; until $i > $num  do puts(&quot;Inside the loop i = #$i&quot; ); $i +=1; end This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4 Inside the loop i = 5
Ruby until modifier: Syntax: code until conditional OR begin code end until conditional Executes code while conditional is false. If an until modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated.
Example: $i = 0; $num = 5; begin puts(&quot;Inside the loop i = #$i&quot; ); $i +=1; end until $i > $num This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4 Inside the loop i = 5
Ruby for Statement: Syntax: for variable [, variable ...] in expression [do] code end Executes code once for each element in expression.
Example: for i in 0..5 puts &quot;Value of local variable is #{i}&quot; end Here we have defined the range 0..5. The statement for i in 0..5 will allow i to take values in the range from 0 to 5 (including 5). This will produce following result: Value of local variable is 0 Value of local variable is 1 Value of local variable is 2 Value of local variable is 3 Value of local variable is 4 Value of local variable is 5
A for...in loop is almost exactly equivalent to: Syntax (expression).each do |variable[, variable...]| code end except that a for loop doesn't create a new scope for local variables. A for loop's expression is separated from code by the reserved word do, a newline, or a semicolon.
Example: (0..5).each do |i| puts &quot;Value of local variable is #{i}&quot; end This will produce following result: Value of local variable is 0 Value of local variable is 1 Value of local variable is 2 Value of local variable is 3 Value of local variable is 4 Value of local variable is 5
Ruby break Statement: Syntax: break Terminates the most internal loop. Terminates a method with an associated block if called within the block (with the method returning nil).
Example: for i in 0..5 if i > 2 then break end puts &quot;Value of local variable is #{i}&quot; end This will produce following result: Value of local variable is 0 Value of local variable is 1 Value of local variable is 2
Ruby next Statement: Syntax: next Jumps to next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil).
Example: for i in 0..5 if i < 2 then next end puts &quot;Value of local variable is #{i}&quot; end This will produce following result: Value of local variable is 2 Value of local variable is 3 Value of local variable is 4 Value of local variable is 5
Ruby redo Statement: Syntax: redo Restarts this iteration of the most internal loop, without checking loop condition. Restarts yield or call if called within a block.
Example: for i in 0..5 if i < 2 then puts &quot;Value of local variable is #{i}&quot; redo end end This will produce following result and will go in an infinite loop: Value of local variable is 0 Value of local variable is 0 ............................
Ruby retry Statement: Syntax: retry If retry appears in rescue clause of begin expression, restart from the beginning of the 1begin body. 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
Example: for i in 1..5 retry if  i > 2 puts &quot;Value of local variable is #{i}&quot; end This will produce following result and will go in an infinite loop: Value of local variable is 1 Value of local variable is 2 Value of local variable is 1 Value of local variable is 2 Value of local variable is 1 Value of local variable is 2 ............................
Ruby Methods Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit. Method names should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly. Methods should be defined before calling them otherwise Ruby will raise an exception for undefined method invoking. Syntax: def method_name [( [arg [= default]]...[, * arg [, &expr ]])] expr.. end
So you can define a simple method as follows: def method_name  expr.. end You can represent a method that accepts parameters like this: def method_name (var1, var2) expr.. end You can set default values for the parameters which will be used if method is called without passing required parameters: def method_name (var1=value1, var2=value2) expr.. end
Example: def test(a1=&quot;Ruby&quot;, a2=&quot;Perl&quot;) puts &quot;The programming language is #{a1}&quot; puts &quot;The programming language is #{a2}&quot; end test &quot;C&quot;, &quot;C++&quot; test This will produce following result: The programming language is C The programming language is C++ The programming language is Ruby The programming language is Perl
Example: def test i = 100 j = 200 k = 300 return i, j, k end var = test puts var This will produce following result: 100 200 300
Example: def sample (*test) puts &quot;The number of parameters is #{test.length}&quot; for i in 0...test.length puts &quot;The parameters are #{test[i]}&quot; end end sample &quot;Zara&quot;, &quot;6&quot;, &quot;F&quot; sample &quot;Mac&quot;, &quot;36&quot;, &quot;M&quot;, &quot;MCA&quot; 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 You have seen how Ruby defines methods where you can put number of statements and then you call that method. Similarly Ruby has a concept of Bolck. A block consists of chunks of code. You assign a name to a block. The code in the block is always enclosed within braces ({}). A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the name test, then you use the function test to invoke this block. You invoke a block by using the yield statement.
Syntax: block_name{ statement1 statement2 .......... } Here you will learn to invoke a block by using a simple yield statement. You will also learn to use a yield statement with parameters for invoking a block. You will check the sample code with both types of yield statements.
The yield Statement: Let us look at an example of the yield statement: def test puts &quot;You are in the method&quot; yield puts &quot;You are again back to the method&quot; yield end test {puts &quot;You are in the block&quot;} This will produce following result: You are in the method You are in the block You are again back to the method You are in the block
You also can pass parameters with the yield statement. Here is an  example: def test yield 5 puts &quot;You are in the method test&quot; yield 100 end test {|i| puts &quot;You are in the block #{i}&quot;} This will produce following result: You are in the block 5 You are in the method test You are in the block 100 Here the yield statement is written followed by parameters. You can even pass more than one parameter. In the block, you place a variable between two vertical lines (||) to accept the parameters. Therefore, in the preceding code, the yield 5 statement passes the value 5 as a parameter to the test block.
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
Inheritance is a relation between two classes.  Inheritance is indicated with <. 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-Oriented Portable Automatic Memory-Management (garbage collection) Easy And Clear Syntax Case Sensitive  Lowercase letters and uppercase letters are distinct. The keyword end, for example, is completely different from the keyword END. and features
Statement Delimiters  Multiple statements on one line must be separated by semicolons, but they are not required at the end of a line; a linefeed is treated like a semicolon.  Keywords  Also known as reserved words in Ruby typically cannot be used for other purposes. A dynamic, open source programming language with a focus on simplicity and productivity Open Source
Basic Networking Our discussion of networking focuses on both sides of a client-server relationship.  The client requests that some action be performed, and the server performs the action and responds to the client. A common implementation of the request-response model is between World Wide Web browsers and World Wide Web servers. When a user selects a Web site to browse through a browser (the client application), a request is sent to the appropriate Web server (the server application). The server normally responds to the client by sending an appropriate HTML Web page.
Port A port is not a physical device In computer networking, a  port number  is part of the addressing information used to identify the senders and receivers of messages.  A port is an abstraction to facilitate communication between a server and a client. Ports are described by a 16-bit integer value. Ranging from 0 to 65535  Hence, a machine can have a maximum of 65536 port numbers
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. These are the numerical host addresses that consist of four bytes such as 132.163.4.102 ( i.e 32-bit number).  An Internet Protocol (IP) address is a numerical label that is assigned to devices participating in a computer network utilizing the Internet Protocol for communication between its nodes. Internet Addresses The IP address 127.0.0.1 (localhost) is a special address, called the local loopback address, which denotes the local machine.
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
SOAP4R is the SOAP implementation for Ruby  developed by Hiroshi Nakamura  The soap4r module is bundled with modern versions of Ruby 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.
Load the soap4r library: require 'soap/wsdlDriver' Get the service proxy for the service: # URL for the service WSDL wsdl = 'http://www.ebi.ac.uk/Tools/webservices/wsdl/WSDbfetch.wsdl' # Get the object from the WSDL dbfetchSrv = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver For debugging it is useful to see the SOAP messages being passed between the client and the server: dbfetchSrv.wiredump_dev = STDOUT Get the data from the service and print it: puts dbfetchSrv.fetchData(&quot;UNIPROT:ADH1A_HUMAN&quot;, &quot;fasta&quot;, &quot;raw&quot;)

More Related Content

PPTX
Ruby Programming Language - Introduction
PDF
Introduction to Ruby
PPTX
Java 8 Lambda and Streams
PPTX
Ruby programming
ODP
PDF
The New JavaScript: ES6
PDF
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
PDF
Ruby Presentation
Ruby Programming Language - Introduction
Introduction to Ruby
Java 8 Lambda and Streams
Ruby programming
The New JavaScript: ES6
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Ruby Presentation

What's hot (20)

PPTX
Rest api with node js and express
PPTX
Node.js Express
PDF
ES6 presentation
PPTX
Java Beans
PDF
Express node js
PDF
Introduction to Ruby
PPTX
Introduction to es6
ODP
Introduction to Java 8
PPT
Java Collections Framework
PPT
Java collections concept
PPTX
Dom(document object model)
PPSX
Collections - Maps
PDF
Arrays in Java
PPTX
Chapter 07 inheritance
PPTX
Javascript functions
PPTX
Hibernate ppt
PDF
Angular - Chapter 7 - HTTP Services
PPTX
JavaScript
PPTX
Polymorphism presentation in java
Rest api with node js and express
Node.js Express
ES6 presentation
Java Beans
Express node js
Introduction to Ruby
Introduction to es6
Introduction to Java 8
Java Collections Framework
Java collections concept
Dom(document object model)
Collections - Maps
Arrays in Java
Chapter 07 inheritance
Javascript functions
Hibernate ppt
Angular - Chapter 7 - HTTP Services
JavaScript
Polymorphism presentation in java
Ad

Viewers also liked (20)

PDF
Ruby on Rails Presentation
PDF
Ruby on Rails for beginners
PDF
Ruby on Rails Presentation
PDF
Why Ruby
PDF
Reflection in Ruby
PDF
PHP Loops and PHP Forms
PPT
Ruby on Rails small application demo
PPTX
Programming Basics - array, loops, funcitons
PDF
Ruby On Rails - Porque Utilizar?
PDF
Express 4
PPTX
Welcome to ruby!
PPTX
Ruby data types and objects
PPTX
Loops PHP 04
PDF
Ruby on rails porque usar rails?!
PDF
Память руби изнутри
PDF
Programming for the non-programmer
PDF
PHP vs. Ruby on Rails
PDF
Ruby Data Types and Data Structures
PDF
Ruby On Rails Basics
PPTX
Sapphire Presentation for Review_CPG_Food.PPTX
Ruby on Rails Presentation
Ruby on Rails for beginners
Ruby on Rails Presentation
Why Ruby
Reflection in Ruby
PHP Loops and PHP Forms
Ruby on Rails small application demo
Programming Basics - array, loops, funcitons
Ruby On Rails - Porque Utilizar?
Express 4
Welcome to ruby!
Ruby data types and objects
Loops PHP 04
Ruby on rails porque usar rails?!
Память руби изнутри
Programming for the non-programmer
PHP vs. Ruby on Rails
Ruby Data Types and Data Structures
Ruby On Rails Basics
Sapphire Presentation for Review_CPG_Food.PPTX
Ad

Similar to Ruby Basics (20)

PDF
10 ruby loops
PDF
09 ruby if else
PPTX
Ruby is a dynamic, reflective, object-oriented, general-purpose programming l...
PDF
04 ruby syntax
PPTX
Case, Loop & Command line args un Unix
PPT
Ruby for C# Developers
PPTX
Ruby -the wheel Technology
PDF
1669958779195.pdf
PPTX
Php Loop
PPTX
Switch case and looping jam
PPTX
Getting started in c++
PPTX
PPT
P H P Part I, By Kian
PPTX
Switch case and looping new
PPTX
Macasu, gerrell c.
PDF
Comprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
PDF
JavaScript Cheatsheets with easy way .pdf
PPTX
My final requirement
PPT
Ruby Hell Yeah
10 ruby loops
09 ruby if else
Ruby is a dynamic, reflective, object-oriented, general-purpose programming l...
04 ruby syntax
Case, Loop & Command line args un Unix
Ruby for C# Developers
Ruby -the wheel Technology
1669958779195.pdf
Php Loop
Switch case and looping jam
Getting started in c++
P H P Part I, By Kian
Switch case and looping new
Macasu, gerrell c.
Comprehensive JavaScript Cheat Sheet for Quick Reference and Mastery
JavaScript Cheatsheets with easy way .pdf
My final requirement
Ruby Hell Yeah

More from SHC (20)

PPT
Perform brute force
 
PPT
AJAX ASP.Net
 
PDF
C++ plus data structures, 3rd edition (2003)
 
PDF
Inside Asp.Net Web Matrix
 
PDF
V Pro Bp08505 Phase Iii Edited
 
DOC
V Pro Bp08505 Phase Iii Edited
 
DOC
V Pro Bp08505 Phase Ii Edited
 
PDF
Intel® V Pro™ Technology
 
PPT
XForms with Linux
 
PPT
XForms
 
PPT
Rails
 
PPT
Call
 
PPTX
Action Mailer
 
PPT
Ruby Security
 
PPTX
Web Services
 
PDF
Pragmatic Agile Web Development With Rails.3rd Edition.2009
 
PPT
Ruby Installation
 
PPT
Mysql Statments
 
PPT
Mysql Fun
 
PPT
Mysql
 
Perform brute force
 
AJAX ASP.Net
 
C++ plus data structures, 3rd edition (2003)
 
Inside Asp.Net Web Matrix
 
V Pro Bp08505 Phase Iii Edited
 
V Pro Bp08505 Phase Iii Edited
 
V Pro Bp08505 Phase Ii Edited
 
Intel® V Pro™ Technology
 
XForms with Linux
 
XForms
 
Rails
 
Call
 
Action Mailer
 
Ruby Security
 
Web Services
 
Pragmatic Agile Web Development With Rails.3rd Edition.2009
 
Ruby Installation
 
Mysql Statments
 
Mysql Fun
 
Mysql
 

Recently uploaded (20)

PPTX
Machine Learning_overview_presentation.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
Spectroscopy.pptx food analysis technology
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Electronic commerce courselecture one. Pdf
Machine Learning_overview_presentation.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Approach and Philosophy of On baking technology
Network Security Unit 5.pdf for BCA BBA.
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Spectroscopy.pptx food analysis technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Mobile App Security Testing_ A Comprehensive Guide.pdf
SOPHOS-XG Firewall Administrator PPT.pptx
Encapsulation_ Review paper, used for researhc scholars
Building Integrated photovoltaic BIPV_UPV.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
MYSQL Presentation for SQL database connectivity
Per capita expenditure prediction using model stacking based on satellite ima...
20250228 LYD VKU AI Blended-Learning.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
NewMind AI Weekly Chronicles - August'25-Week II
Electronic commerce courselecture one. Pdf

Ruby Basics

  • 1. Ruby was introduced by Yukihiro Matsumoto (known widely as “Matz”) Ruby originated in Japan during the mid-1990s Ruby is Based on Perl,Smalltalk,Eiffel,Ada and Lisp. Ruby offers automatic memory management. Ruby is Written in c Ruby is a dynamic interpreted language which has many strong features of various languages. It is a strong Object oriented programming language. Ruby is open source Ruby can be embeded into Hypertext Markup Language (HTML). Ruby has similar syntax to that of many programming languages such as C++ and Perl. Ruby Introduction
  • 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. Ruby BEGIN Statement Syntax: BEGIN { code } Declares code to be called before the program is run. Example: puts &quot;This is main Ruby Program&quot; BEGIN { puts &quot;Initializing Ruby Program&quot; } This will produce following result: Initializing Ruby Program This is main Ruby Program
  • 4. Ruby END Statement Syntax: END { code } Declares code to be called at the end of the program.
  • 5. Example: puts &quot;This is main Ruby Program&quot; END { puts &quot;Terminating Ruby Program&quot; } BEGIN { puts &quot;Initializing Ruby Program&quot; } This will produce following result: Initializing Ruby Program This is main Ruby Program Terminating Ruby Program
  • 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. Ruby Arithmetic Operators: Ruby Operators ** Exponent - Performs exponential (power) calculation on operators a**b will give 10 to the power 20 Example 2**3=>8
  • 9. Ruby Comparison Operators: <=> Combined comparison operator. Return 0 if first operand equals second Return 1 if first operand is greater than the second. Return -1 if first operand is less than the second. (a <=> b) returns -1. Example
  • 10. eql? True if the receiver and argument have both the same type and equal values. Example 1 == 1.0 returns true, but 1.eql?(1.0) is false. Ruby Logical Operators: and Called Logical AND operator. If both the operands are true then then condition becomes true. Example (a and b) is true.
  • 11. or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. Example (a or b) is true. not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. Example not(a && b) is false.
  • 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. Ruby defined? operators: defined? is a special operator that takes the form of a method call to determine whether or not the passed expression is defined. It returns a description string of the expression, or nil if the expression isn't defined. There are various usage of defined? operator: defined? variable # True if variable is initialized Example foo = 42 defined? foo # => &quot;local-variable&quot; defined? $_ # => &quot;global-variable&quot; defined? bar # => nil (undefined)
  • 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. Ruby offers contional structures that are pretty common to modern languages. Here we will explain all the Conditional Statements and modifiers available in Ruby Ruby if...else Statement: Syntax: if conditional [then] code... [elsif conditional [then] code...]... [else code...] end
  • 16. if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif. Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed. An if expression's conditional is separated from code by the reserved word then , a newline, or a semicolon.
  • 17. Example: x=1 if x > 2 puts &quot;x is greater than 2&quot; elsif x <= 2 and x!=0 puts &quot;x is 1&quot; else puts &quot;I can't guess the number&quot; end Output x is 1
  • 18. Ruby if modifier: Syntax: code if condition Executes code if the conditional is true. Example: $debug=1 print &quot;debug\n&quot; if $debug Output: debug
  • 19. Ruby unless Statement: Syntax: unless conditional [then] code [else code ] end Executes code if conditional is false. If the conditional is true, code specified in the else clause is executed.
  • 20. Example: x=1 unless x>2 puts &quot;x is less than 2&quot; else puts &quot;x is greater than 2&quot; end This will produce following result: x is less than 2
  • 21. Ruby unless modifier: Syntax: code unless conditional Executes code if conditional is false. Example: $var = 1 print &quot;1 -- Value is set\n&quot; if $var print &quot;2 -- Value is set\n&quot; unless $var $var = false print &quot;3 -- Value is set\n&quot; unless $var This will produce following result: 1 -- Value is set 3 -- Value is set
  • 22. Ruby case Statement Syntax: case expression [when expression [, expression ...] [then] code ]... [else code ] end Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches. The expression specified by the when clause is evaluated as the left operand. If no when clauses match, case executes the code of the else clause. A when statement's expression is separated from code by the reserved word then, a newline, or a semicolon.
  • 23. Example: $age = 5 case $age when 0 .. 2 puts &quot;baby&quot; when 3 .. 6 puts &quot;little child&quot; when 7 .. 12 puts &quot;child&quot; when 13 .. 18 puts &quot;youth&quot; else puts &quot;adult&quot; end This will produce following result: little child
  • 24. 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. Ruby while Statement: Syntax: while conditional [do] code end Executes code while conditional is true. A while loop's conditional is separated from code by the reserved word do, a newline, backslash \, or a semicolon ;.
  • 25. Example: $i = 0; $num = 5; while $i < $num do puts(&quot;Inside the loop i = #$i&quot; ); $i +=1; end This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4
  • 26. Ruby while modifier: Syntax: code while condition OR begin code end while conditional Executes code while conditional is true. If a while modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated.
  • 27. Example: $i = 0; $num = 5; begin puts(&quot;Inside the loop i = #$i&quot; ); $i +=1; end while $i < $num This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4
  • 28. Ruby until Statement: Syntax: until conditional [do] code end Executes code while conditional is false. An until statement's conditional is separated from code by the reserved word do, a newline, or a semicolon.
  • 29. Example: $i = 0; $num = 5; until $i > $num do puts(&quot;Inside the loop i = #$i&quot; ); $i +=1; end This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4 Inside the loop i = 5
  • 30. Ruby until modifier: Syntax: code until conditional OR begin code end until conditional Executes code while conditional is false. If an until modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated.
  • 31. Example: $i = 0; $num = 5; begin puts(&quot;Inside the loop i = #$i&quot; ); $i +=1; end until $i > $num This will produce following result: Inside the loop i = 0 Inside the loop i = 1 Inside the loop i = 2 Inside the loop i = 3 Inside the loop i = 4 Inside the loop i = 5
  • 32. Ruby for Statement: Syntax: for variable [, variable ...] in expression [do] code end Executes code once for each element in expression.
  • 33. Example: for i in 0..5 puts &quot;Value of local variable is #{i}&quot; end Here we have defined the range 0..5. The statement for i in 0..5 will allow i to take values in the range from 0 to 5 (including 5). This will produce following result: Value of local variable is 0 Value of local variable is 1 Value of local variable is 2 Value of local variable is 3 Value of local variable is 4 Value of local variable is 5
  • 34. A for...in loop is almost exactly equivalent to: Syntax (expression).each do |variable[, variable...]| code end except that a for loop doesn't create a new scope for local variables. A for loop's expression is separated from code by the reserved word do, a newline, or a semicolon.
  • 35. Example: (0..5).each do |i| puts &quot;Value of local variable is #{i}&quot; end This will produce following result: Value of local variable is 0 Value of local variable is 1 Value of local variable is 2 Value of local variable is 3 Value of local variable is 4 Value of local variable is 5
  • 36. Ruby break Statement: Syntax: break Terminates the most internal loop. Terminates a method with an associated block if called within the block (with the method returning nil).
  • 37. Example: for i in 0..5 if i > 2 then break end puts &quot;Value of local variable is #{i}&quot; end This will produce following result: Value of local variable is 0 Value of local variable is 1 Value of local variable is 2
  • 38. Ruby next Statement: Syntax: next Jumps to next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil).
  • 39. Example: for i in 0..5 if i < 2 then next end puts &quot;Value of local variable is #{i}&quot; end This will produce following result: Value of local variable is 2 Value of local variable is 3 Value of local variable is 4 Value of local variable is 5
  • 40. Ruby redo Statement: Syntax: redo Restarts this iteration of the most internal loop, without checking loop condition. Restarts yield or call if called within a block.
  • 41. Example: for i in 0..5 if i < 2 then puts &quot;Value of local variable is #{i}&quot; redo end end This will produce following result and will go in an infinite loop: Value of local variable is 0 Value of local variable is 0 ............................
  • 42. Ruby retry Statement: Syntax: retry If retry appears in rescue clause of begin expression, restart from the beginning of the 1begin body. 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
  • 43. Example: for i in 1..5 retry if i > 2 puts &quot;Value of local variable is #{i}&quot; end This will produce following result and will go in an infinite loop: Value of local variable is 1 Value of local variable is 2 Value of local variable is 1 Value of local variable is 2 Value of local variable is 1 Value of local variable is 2 ............................
  • 44. Ruby Methods Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit. Method names should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly. Methods should be defined before calling them otherwise Ruby will raise an exception for undefined method invoking. Syntax: def method_name [( [arg [= default]]...[, * arg [, &expr ]])] expr.. end
  • 45. So you can define a simple method as follows: def method_name expr.. end You can represent a method that accepts parameters like this: def method_name (var1, var2) expr.. end You can set default values for the parameters which will be used if method is called without passing required parameters: def method_name (var1=value1, var2=value2) expr.. end
  • 46. Example: def test(a1=&quot;Ruby&quot;, a2=&quot;Perl&quot;) puts &quot;The programming language is #{a1}&quot; puts &quot;The programming language is #{a2}&quot; end test &quot;C&quot;, &quot;C++&quot; test This will produce following result: The programming language is C The programming language is C++ The programming language is Ruby The programming language is Perl
  • 47. Example: def test i = 100 j = 200 k = 300 return i, j, k end var = test puts var This will produce following result: 100 200 300
  • 48. Example: def sample (*test) puts &quot;The number of parameters is #{test.length}&quot; for i in 0...test.length puts &quot;The parameters are #{test[i]}&quot; end end sample &quot;Zara&quot;, &quot;6&quot;, &quot;F&quot; sample &quot;Mac&quot;, &quot;36&quot;, &quot;M&quot;, &quot;MCA&quot; 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
  • 49. Ruby Blocks You have seen how Ruby defines methods where you can put number of statements and then you call that method. Similarly Ruby has a concept of Bolck. A block consists of chunks of code. You assign a name to a block. The code in the block is always enclosed within braces ({}). A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the name test, then you use the function test to invoke this block. You invoke a block by using the yield statement.
  • 50. Syntax: block_name{ statement1 statement2 .......... } Here you will learn to invoke a block by using a simple yield statement. You will also learn to use a yield statement with parameters for invoking a block. You will check the sample code with both types of yield statements.
  • 51. The yield Statement: Let us look at an example of the yield statement: def test puts &quot;You are in the method&quot; yield puts &quot;You are again back to the method&quot; yield end test {puts &quot;You are in the block&quot;} This will produce following result: You are in the method You are in the block You are again back to the method You are in the block
  • 52. You also can pass parameters with the yield statement. Here is an example: def test yield 5 puts &quot;You are in the method test&quot; yield 100 end test {|i| puts &quot;You are in the block #{i}&quot;} This will produce following result: You are in the block 5 You are in the method test You are in the block 100 Here the yield statement is written followed by parameters. You can even pass more than one parameter. In the block, you place a variable between two vertical lines (||) to accept the parameters. Therefore, in the preceding code, the yield 5 statement passes the value 5 as a parameter to the test block.
  • 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. Inheritance is a relation between two classes. Inheritance is indicated with <. 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
  • 58. Features of Ruby Object-Oriented Portable Automatic Memory-Management (garbage collection) Easy And Clear Syntax Case Sensitive Lowercase letters and uppercase letters are distinct. The keyword end, for example, is completely different from the keyword END. and features
  • 59. Statement Delimiters Multiple statements on one line must be separated by semicolons, but they are not required at the end of a line; a linefeed is treated like a semicolon. Keywords Also known as reserved words in Ruby typically cannot be used for other purposes. A dynamic, open source programming language with a focus on simplicity and productivity Open Source
  • 60. Basic Networking Our discussion of networking focuses on both sides of a client-server relationship. The client requests that some action be performed, and the server performs the action and responds to the client. A common implementation of the request-response model is between World Wide Web browsers and World Wide Web servers. When a user selects a Web site to browse through a browser (the client application), a request is sent to the appropriate Web server (the server application). The server normally responds to the client by sending an appropriate HTML Web page.
  • 61. Port A port is not a physical device In computer networking, a port number is part of the addressing information used to identify the senders and receivers of messages. A port is an abstraction to facilitate communication between a server and a client. Ports are described by a 16-bit integer value. Ranging from 0 to 65535 Hence, a machine can have a maximum of 65536 port numbers
  • 62. 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. These are the numerical host addresses that consist of four bytes such as 132.163.4.102 ( i.e 32-bit number). An Internet Protocol (IP) address is a numerical label that is assigned to devices participating in a computer network utilizing the Internet Protocol for communication between its nodes. Internet Addresses The IP address 127.0.0.1 (localhost) is a special address, called the local loopback address, which denotes the local machine.
  • 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. SOAP4R is the SOAP implementation for Ruby developed by Hiroshi Nakamura The soap4r module is bundled with modern versions of Ruby 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.
  • 74. Load the soap4r library: require 'soap/wsdlDriver' Get the service proxy for the service: # URL for the service WSDL wsdl = 'http://www.ebi.ac.uk/Tools/webservices/wsdl/WSDbfetch.wsdl' # Get the object from the WSDL dbfetchSrv = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver For debugging it is useful to see the SOAP messages being passed between the client and the server: dbfetchSrv.wiredump_dev = STDOUT Get the data from the service and print it: puts dbfetchSrv.fetchData(&quot;UNIPROT:ADH1A_HUMAN&quot;, &quot;fasta&quot;, &quot;raw&quot;)