Ruby is a dynamic, interpreted programming language introduced by Yukihiro Matsumoto in the mid-1990s, deriving features from multiple languages like Perl and Smalltalk. It supports automatic memory management, strong object-oriented programming, and a syntax reminiscent of languages like C++ and Perl. Key concepts include methods, loops, conditional structures, and operators for arithmetic, comparison, and logical operations.
Ruby was introducedby 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 writea 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!
3.
Ruby BEGIN StatementSyntax: 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
4.
Ruby END StatementSyntax: END { code } Declares code to be called at the end of the program.
5.
Example: puts "Thisis 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
6.
Ruby Comments: Acomment 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.
7.
Here is anotherform. 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 ifthe 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 LogicalOR 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 ".." and "..." 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 # => "local-variable" defined? $_ # => "global-variable" 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 contionalstructures 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 expressionsare 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 ifx > 2 puts "x is greater than 2" elsif x <= 2 and x!=0 puts "x is 1" else puts "I can't guess the number" end Output x is 1
18.
Ruby if modifier:Syntax: code if condition Executes code if the conditional is true. Example: $debug=1 print "debug\n" 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 unlessx>2 puts "x is less than 2" else puts "x is greater than 2" 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 "1 -- Value is set\n" if $var print "2 -- Value is set\n" unless $var $var = false print "3 -- Value is set\n" unless $var This will produce following result: 1 -- Value is set 3 -- Value is set
22.
Ruby case StatementSyntax: 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 "baby" when 3 .. 6 puts "little child" when 7 .. 12 puts "child" when 13 .. 18 puts "youth" else puts "adult" end This will produce following result: little child
24.
Loops in Rubyare 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("Inside the loop i = #$i" ); $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("Inside the loop i = #$i" ); $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("Inside the loop i = #$i" ); $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("Inside the loop i = #$i" ); $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 iin 0..5 puts "Value of local variable is #{i}" 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 loopis 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 "Value of local variable is #{i}" 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 iin 0..5 if i > 2 then break end puts "Value of local variable is #{i}" 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 iin 0..5 if i < 2 then next end puts "Value of local variable is #{i}" 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 iin 0..5 if i < 2 then puts "Value of local variable is #{i}" 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 iin 1..5 retry if i > 2 puts "Value of local variable is #{i}" 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 Rubymethods 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 candefine 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="Ruby",a2="Perl") puts "The programming language is #{a1}" puts "The programming language is #{a2}" end test "C", "C++" 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 testi = 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 "The number of parameters is #{test.length}" for i in 0...test.length puts "The parameters are #{test[i]}" end end sample "Zara", "6", "F" sample "Mac", "36", "M", "MCA" 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 Youhave 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{ statement1statement2 .......... } 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 "You are in the method" yield puts "You are again back to the method" yield end test {puts "You are in the block"} 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 canpass parameters with the yield statement. Here is an example: def test yield 5 puts "You are in the method test" yield 100 end test {|i| puts "You are in the block #{i}"} 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 aRuby 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 "Customer id #@cust_id" puts "Customer name #@cust_name" puts "Customer address #@cust_addr" end def total_no_of_customers() @@no_of_customers += 1 puts "Total number of customers: #@@no_of_customers" end end # Create Objects cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala") # Call Methods cust1.display_details() cust1.total_no_of_customers() cust2.display_details() cust2.total_no_of_customers()
56.
Output Customer id1 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 arelation between two classes. Inheritance is indicated with <. class Mammal def breathe puts "inhale and exhale" end end class Cat < Mammal def speak puts "Meow" end end rani = Cat.new rani.breathe rani.speak Inheritance
58.
Features of RubyObject-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 Ourdiscussion 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 portis 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 worklike 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 developsockets-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 Usageof 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 writeInternet 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 "Closing the connection. Bye!" client.close # Disconnect from the client } Now run this server in background and then run above client to see the result.
68.
The Date TimeServer 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 "Closing the connection. Bye!" client.close # Disconnect from the client }
69.
Explanation of theabove 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 codefor the Date Time Client require 'socket' streamSock = TCPSocket.new( "127.0.0.1", 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 withRuby 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("UNIPROT:ADH1A_HUMAN", "fasta", "raw") end
73.
SOAP4R is theSOAP 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 soap4rlibrary: 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("UNIPROT:ADH1A_HUMAN", "fasta", "raw")