Ruby Basics
Ruby Basics
Ruby is Written in c
ruby test.rb
Hello, Ruby!
Ruby BEGIN Statement
Syntax:
BEGIN {
code
}
Example:
BEGIN {
puts "Initializing Ruby Program"
}
Syntax:
END {
code
}
END {
puts "Terminating Ruby Program"
}
BEGIN {
puts "Initializing Ruby Program"
}
# 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 Operators
**
Example
2**3=>8
Ruby Comparison Operators:
<=>
Example
Example
and
Example
(a and b) is true.
or
Example
(a or b) is true.
not
Example
Description Example
Operator
Creates a range from
1..10 Creates a range from 1 to 10
.. start point to end
inclusive
point inclusive
Creates a range from
... start point to end 1...10 Creates a range from 1 to 9
point exclusive
Ruby defined? operators:
Example
foo = 42
defined? foo # => "local-variable"
defined? $_ # => "global-variable"
defined? bar # => nil (undefined)
Ruby Parallel Assignment:
a = 10
b = 20
c = 30
a, b, c = 10, 20, 30
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
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.
x=1
if x > 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
Ruby if modifier:
Syntax:
code if condition
Example:
$debug=1
print "debug\n" if $debug
Output:
debug
Ruby unless Statement:
Syntax:
x=1
unless x>2
puts "x is less than 2"
else
puts "x is greater than 2"
end
x is less than 2
Ruby unless modifier:
Syntax:
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
1 -- Value is set
3 -- Value is set
Ruby case Statement
Syntax:
case expression
[when expression [, expression ...] [then]
code ]...
[else
code ]
end
$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
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.
Syntax:
$i = 0;
$num = 5;
Syntax:
OR
begin
code
end while conditional
$i = 0;
$num = 5;
begin
puts("Inside the loop i = #$i" );
$i +=1;
end while $i < $num
Syntax:
$i = 0;
$num = 5;
Syntax:
OR
begin
code
end until conditional
$i = 0;
$num = 5;
begin
puts("Inside the loop i = #$i" );
$i +=1;
end until $i > $num
Syntax:
for i in 0..5
puts "Value of local variable is #{i}"
end
Syntax
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 "Value of local variable is #{i}"
end
Syntax:
break
for i in 0..5
if i > 2 then
break
end
puts "Value of local variable is #{i}"
end
Syntax:
next
for i in 0..5
if i < 2 then
next
end
puts "Value of local variable is #{i}"
end
Syntax:
redo
for i in 0..5
if i < 2 then
puts "Value of local variable is #{i}"
redo
end
end
Syntax:
retry
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 "Value of local variable is #{i}"
end
Syntax:
def method_name
expr..
end
You can set default values for the parameters which will be used if
method is called without passing required parameters:
def test
i = 100
j = 200
k = 300
return i, j, k
end
var = test
puts var
100
200
300
Example:
Output
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.
block_name{
statement1
statement2
..........
}
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"}
def test
yield 5
puts "You are in the method test"
yield 100
end
test {|i| puts "You are in the block #{i}"}
# 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()
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
class Mammal
def breathe
puts "inhale and exhale"
end
end
rani = Cat.new
rani.breathe
rani.speak
Features of Ruby
Object-Oriented
Portable
Case Sensitive
Keywords
Open Source
The client requests that some action be performed, and the server
performs the action and responds to the client.
Internet Addresses
These are the numerical host addresses that consist of four bytes such
as 132.163.4.102 ( i.e 32-bit number).
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.
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.
host = 'localhost'
port = 2000
s = TCPSocket.open(host, port)
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
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( "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.
Web Services with Ruby
What is SOAP ?
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
require 'soap/wsdlDriver'
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