Java Socket’s Fundamentals – Ruby on Rails tutorial

UNIX has many advanced techniques and one of them is Java Socket. It gives permission to use network connection as a way of writing and reading bytes. The connection of Java socket can be dependent upon 2 hosts. Server and Socket are the two types of Java sockets. One is used for server and the other is used for clients. Java socket can perform the following functions:
• Attach to machine
• Drive data
• Accept data
• Shut a machine
• Join to port
• Pay attention for coming data
• Allow connections commencing on port from machines

Java Socket and Java Socket Server

Java Socket Basic
Clients’ Java Socket
client socket’s duration
With the use of class constructor, a fresh socket is made.
Socket makes efforts for bonding to a distant host.
A distant and local host can swap their information when connection gets established. It is also possible that the data can be relocated at the same time by server and client.
Connection can be stopped when the broadcast gets completed.
In order to carry out operations related to clients, Java.net.Socket can be known as the basic class.
Connection can be initialized or stopped by Socket class method. A programmer can get flow from mentioned class.
Constructors
There are four socket class constructors where hosts are known as string or IntelAddress. Ports are known as int whose value starts from 0 up to 65,535.
1) UnknownExceptions and IOException are thrown by public Socket
A certain host having certain port will get TCP socket. This will make an effort for connection to a distant host.
host – string has its description.
port – a host can communicate by a port.
UnknownException- the given exception canl be discarded when host name can not be determined by DNS.
IOException- it starts working when the socket becomes unable to open. Import java.net.*;

import java.io.*;
public class portscan
{
public static void main(String a[])
{
If(a.length>0)
host=a0];
for (int i=1;i<1024;i++)
{
try
{
InetAddress addr=InetAddress.getByName(host);
for(int i=1024;i<65536;i++)
{
try{
Socket s=new Socket(host, i);
System.out.println(“There is a server on port”+i+”of”+host);
}
catch(UnknownHostException ie)
{
System.out.println(ie);
}
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
2) IOException is thrown by public socket having int port and InetAddress host.
A certain host having a certain port will get TCP socket by the above mentioned constructor.
InetAddress host- it mentions the host in spite of the name of the host.

port – it shows the number of port through which host gets communication.

IOException- this function will be performed when the socket will become unable to work.

import java.net.*;
import java.io.*;
public class portserver 1024
{
public static void main(String a[])
{
String host=’localhost’;
If(a.length>0)
host=a0];
for (int i=1;i<1024;i++)
{
try
{
InetAddress addr=InetAddress.getByName(host);
for(int i=1024;i<65536;i++)
{
try{
Socket s=new Socket(addr, i);
System.out.println(“There is a server on port”+i+”of”+host);
}
catch(IOException ie)
{
System.out.println(ie);
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
3) IOException is thrown by public socket having int port, string host, InetAddress and int localport.
By making a socket, it is tried to make connection to a certain port related to a certain host.
host –explained in the form of string.
port – it shows the number through which the host are going to be communicated.
InetAddress intref- its purpose is to make connection commencing from the confined network boundary.
Localport –its purpose is to select a port ranges from 1024 to 65,535.
IOException- it will occur when the socket will become unable to open.
4) IOException is thrown by public socket having int port, InetAddress host, int localport and InetAddress intref.
It gives the connection by InetAddress in spite of the name of the host.
5) ProtectedSocket()
A fresh socket will be built without making any connection.
6) ProtectedSocket(SocketImpl impl)
Without any connection, a fresh socket will be built. If the object has no demand then void will be transferred through constructor.

Information about Socket
There is only 1 field of socket object which is SocketImpl.
There are the methods which are mostly used:
public InetAddress getInetAddress() – it gives information about the distant host to which it is connected or has stopped connection.
public int getPort() – it gives information about the port to which socket connection is made.
public int getLocalPort() – it’s purpose is to know the port no related to connection of confined end.
public InetAddress getLocalAddress() – it’s purpose is to know about the interface of network which is used for socket bounding.
public InputStream getInputStream() throws IOException – gives back input flow which is able to study the data commencing from a socket.
public OutputStream getOutputStream() throws IOException – it gives back OutputStream for the purpose of inscribing data.

Servers with Java Sockets
In order to inscribe server program related to java socket, ServerSocket is used. It searches for coming connection of TCP.
Fundamental life spam of ServerSocketclass•

A ServerSocket()in order to make fresh java socket, constructor is being used. • The ServerSocket() it gives back socket object whenever a client tries for connection. • Sockets getInputStream() or getOutputStream(): their function is to drive and obtain data.
• The connection can be ended by either client or server.
Constructors
1. IOException, BindException is thrown by public ServerSocket(int port)
Java socket will be built over a port. The ports from 1024 headed for 65,535 will be selected when 0 will pass. The system chooses argument ports.
2.IOException, BindException is thrown by public ServerSocket(int port, int queueLength)
It makes queuelength over certain ports for the coming connections by creating ServerSocket.
When 0 will transfer then the ports will be elected. The highest queuelength is determined as five.
3. IOException, BindException is thrown by public ServerSocket(int port, int queueLength InetAddress BindAddress)

It makes a ServerSocket over certain ports by using queuelength. It is used for coming requests. It is best for those systems which have IP address.
How to allow and Close connections
In order to make or stop a connection, there are two methods. This connection has two channels i.e. server and client.
accept() method
public Socket accept() throws IOException
It makes the execution stop till the client tries to construct a connection. It gives back an object.
getInputStream() andgetOutputStream methods are used to swap over data involving server and client.

For instance:
ServerSocket SS= new ServerSocket(6750);
While(true)
{
Socket con = SS.accept();
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.Writer(“connected to server”);
con.close();
}
close() method
public void close() throws IOException
Whenever a program gets ended, it also gets closed by itself. It gives permission to other java socket is in favor of binding in the direction of port.
get() method
There are two methods of ServerSocket. These methods are known as
1. getInetAddress()
It gives back the address which is used through server.
Example
{
ServerSocket SS=new ServerSocket(80);
InetAddress add=SS.getInetAddress();
}
2. getlocalPort()
It gives back a specific port that is used for listening. We can use it for more than one socket programs.
Example
{
ServerSocket SS=new ServerSocket(0);
System.out.println(“The server is on port”+SS.getLocalPort());
}
Selection of Socket
The one and only selection for socket is known as So-TIMEOUT. It is calculation related to time in the form of milliseconds. Here outer connection is being lingered by accept() previous to making interrupton to IOException.
Methods
1. setTimeout(int timeout)
It makes setting of So-TIMEOUT meant for socket server. It starts calculation only when the accept() gets called upon.
2. getTimeout(int timeout)
It gives back the present So-TIMEOUT back to socket server.
Java seminar for generating FTP client – server curriculum
Client Program:
importjava.io.*;
importjava.net.*;
class ftpclient
{
public static void main(String args[])
{
Socket client;
PrintStream ps;
String msg, line;
String fn;
Byte b[]=new Byte[500];
Int i=0;
try
{
Client=new Socket(InetAddress.getByName(“127.0.0.1”,3330);
ps=new PrintStream(client.getOutputStream(),true);
ps.println(“Transfer the file”);
DataInputStream dis=new DataInputStream(client.getInputStream());
FileOutputStream fos=new FileOutputStream(out.txt”);
DataOutputStream dos=new DataOutputStream(fos);
Line=ds.readLine();
System.out.println(“File Transferring…”);
dos.writeCars(line);
System.out.println(“File tTransferred…”);
}
Catch(Exception e)
{
System.out.println(e);
}
}
}

Server Program:
import java.io.*;
import java.net.*;
class FTPServer
{
public static void main(String args[])
{
ServerSocket server;
Socket con;
String msg, ofname;
try
{
Server= new ServerSocket(3330);
con=server.accept();
System.out.println(“Connection established”);
BufferedReader dis= new BufferedReader(new InputStreamReader(con.getInputStream());
String str1=dis.readLine();
System.out.println(“Client”+str1);
System.out.println(“Starting File transfer”);
File f=new File(“file path”);
FileInputStream fis=new FileInputStream;
DataInputStream disf=new DataInputStream(fis);
DataOutputStream dos=new DataOutputStream(con.getoutputStream());
While(msg=disf.reaadLine()!=null)
{
System.out.println(“File transfer complete”);
con.close();
}
}
Catch(Exception e)
{
System.out.println(e);
}
}

Blocks and Procs – Ruby On Rails tutorial

BLOCKS AND PROCS

Now, we are going to explain the most comfortable characteristics of Ruby. It is about code present in the mid of ‘do’ and ‘end’. It is enclosed in a specific object and saved in a specific variable and goes to a certain method. Here, is an example for you;
toast = Proc.new do
puts ‘Cheers!’
end

toast.call
toast.call
toast.call
Cheers!
Cheers!
Cheers!

Here, we have built up a proc having a block with certain codes in it. It is important to know that blocks are able to get parameters.
doYouLike = Proc.new do |aGoodThing|
puts ‘I *really* like ‘+aGoodThing+’!’
end

doYouLike.call ‘chocolate’
doYouLike.call ‘ruby’
I *really* like chocolate!
I *really* like ruby!

Now, the question is that why do we use procs? Can not we complete our work only with methods? The reason is that procs are able to be passed to any other method. But methods have no such quality.
METHODS WHICH ARE ABLE TO GET PROCS

It is possible to take the control of proc as soon as it goes in a method. Here is an example for you:
def doSelfImportantly someProc
puts ‘Everybody just HOLD ON! I have something to do…’
someProc.call
puts ‘Ok everyone, I\’m done. Go on with what you were doing.’
end

sayHello = Proc.new do
puts ‘hello’
end

sayGoodbye = Proc.new do
puts ‘goodbye’
end

doSelfImportantly sayHello
doSelfImportantly sayGoodbye
Everybody just HOLD ON! I have something to do…
hello
Ok everyone, I’m done. Go on with what you were doing.
Everybody just HOLD ON! I have something to do…
goodbye
Ok everyone, I’m done. Go on with what you were doing.
While making a program, we can adjust the requirements in a strict way. In other languages, it is difficult to open or make changes in a file. We have to give commands for opening, saving and closing a file. But in Ruby, opening a file is just like a code.
The interesting thing is that we can determine the calling of a proc in a method. We can select the figure of times a proc can be called.
def maybeDo someProc
if rand(2) == 0
someProc.call
end
end

def twiceDo someProc
someProc.call
someProc.call
end

wink = Proc.new do
puts ‘
end

glance = Proc.new do
puts ‘
end

maybeDo wink
maybeDo glance
twiceDo wink
twiceDo glance





Methods do not give us a chance to do a task more than one time. This facility is offered by procs.

Here is an example in which we will call our proc. In case, the proc comes back with a false value, then we leave it. If the value is not false then we will keep on calling the proc until false value is achieved.
def doUntilFalse firstInput, someProc
input = firstInput
output = firstInput

while output
input = output
output = someProc.call input
end

input
end

buildArrayOfSquares = Proc.new do |array|
lastNumber = array.last
if lastNumber <= 0
false
else
array.pop # Take off the last number…
array.push lastNumber*lastNumber # …and replace it with its square…
array.push lastNumber-1 # …followed by the next smaller number.
end
end

alwaysFalse = Proc.new do |justIgnoreMe|
false
end

puts doUntilFalse([5], buildArrayOfSquares).inspect
puts doUntilFalse(‘I\’m writing this at 3:00 am; someone knock me out!’, alwaysFalse)
[25, 16, 9, 4, 1, 0]
I’m writing this at 3:00 am; someone knock me out!

Here, doUntilFalse could not fulfill our requirement for the next time but alwaysFalse gave the value false for all the time.
PROCS CAN BE RETURENED BY METHODS
The beneficial character of procs is that these can be created in methods as well as can be come back. Here we are going to introduce compose which has 2 methods. It gives back a fresh proc. When this proc is called, it brings the 1st proc and 2nd proc receives the result.
def compose proc1, proc2
Proc.new do |x|
proc2.call(proc1.call(x))
end
end

squareIt = Proc.new do |x|
x * x
end

doubleIt = Proc.new do |x|
x + x
end

doubleThenSquare = compose doubleIt, squareIt
squareThenDouble = compose squareIt, doubleIt

puts doubleThenSquare.call(5)
puts squareThenDouble.call(5)
100
50

SURPASS OF BLOCKS INTO METHODS
It is a bit tough job to define a method then make a proc. After that it is also necessary to call the method by proc. But Ruby gives us a better option where we have no need to utilize the proc after transferring it into method.
It can be understood by using an example:
class Array

def eachEven(&wasABlock_nowAProc)
isEven = true # We start with “true” because arrays start with 0, which is even.

self.each do |object|
if isEven
wasABlock_nowAProc.call object
end

isEven = (not isEven) # Toggle from even to odd, or odd to even.
end
end

end

['apple', 'bad apple', 'cherry', 'durian'].eachEven do |fruit|
puts ‘Yum! I just love ‘+fruit+’ pies, don\’t you?’
end

# Remember, we are getting the even-numbered elements
# of the array, all of which happen to be odd numbers,
# just because I like to cause problems like that.
[1, 2, 3, 4, 5].eachEven do |oddBall|
puts oddBall.to_s+’ is NOT an even number!’
end
Yum! I just love apple pies, don’t you?
Yum! I just love cherry pies, don’t you?
1 is NOT an even number!
3 is NOT an even number!
5 is NOT an even number!
The task is to join our block subsequent to method. By using this way, we can transfer our block within a method. If we have to make our method not to be disregarded then we have to give our proc a name. The name should be given at the very end of the parameter of the method. It must have ampersand.
Once I wished to get to know the exact time of running a program. I inscribed a specific method. It took time for start and end. I knew the exact time through this procedure. This example is also about same procedure:
def profile descriptionOfBlock, &block
startTime = Time.now

block.call

duration = Time.now – startTime

puts descriptionOfBlock+’: ‘+duration.to_s+’ seconds’
end

profile ’25000 doublings’ do
number = 1

25000.times do
number = number + number
end

puts number.to_s.length.to_s+’ digits’ # That is, the number of digits in this HUGE number.
end

profile ‘count to a million’ do
number = 0

1000000.times do
number = number + 1
end
end
7526 digits
25000 doublings: 0.246768 seconds
count to a million: 0.90245 seconds

It has made the things easier than before. We have to put our code in block. After that we have to fling it in profile.
LETS ATTEMPT:
.
1- Make a program which can tell you time after every hour. The procedure ‘Time.now.hour’ will be used for present time.
2- Create a method named as log which gets string explanation of block with a BLOCK as well. Like do ‘SelfImportantly’, it will ‘puts’ a certain string which will announce that the block has initialized as well as the block has finished. This method can be checked by a block code. Within the block, the method log will be called. Log will passed one more block from it. The whole procedure will have the given way:
Beginning “outer block”…
Beginning “some little block”…
…”some little block” finished, returning: 5
Beginning “yet another block”…
…”yet another block” finished, returning: I like Thai food!
…”outer block” finished, returning: false

3- The above method was a bit hard. It can become easy by using a certain variable which can be viewed all the places in the code. It is known as global variable. For this purpose the given name of variable must have $sign. For example
$loggingmethod.
Beginning “outer block”…
Beginning “some little block”…
Beginning “teeny-tiny block”…
…”teeny-tiny block” finished, returning: lots of love
…”some little block” finished, returning: 42
Beginning “yet another block”…
…”yet another block” finished, returning: I love Indian food!
…”outer block” finished, returning: true

Classes – Ruby on Rails tutorial

CLASSES

In order to build a fresh object related to a specific class, the procedure is to write ‘new’.

a = Array.new  + [12345]  #  Array  addition.
b = String.new + 'hello'  #  String addition.
c = Time.new

puts 'a = '+a.to_s
puts 'b = '+b.to_s
puts 'c = '+c.to_s
a = 12345
b = hello
c = Tue Apr 14 16:29:20 GMT 2009

As we can make new strings and arrays by writing ‘…’ and […..], that’s why new is not as much used.
TIME CLASS

This class shows the moment in the form of time. In order to make change in time, we have to add numbers in it.
time = Time.new # The moment I generated this web page.
time2 = time + 60 # One minute later.

puts time
puts time2
Tue Apr 14 16:29:20 GMT 2009
Tue Apr 14 16:30:20 GMT 2009
It is also possible to create time related to a certain moment by typing Time.mktime.
puts Time.mktime(2000, 1, 1) # Y2K.
puts Time.mktime(1976, 8, 3, 10, 11) # When I was born.
Sat Jan 01 00:00:00 GMT 2000
Tue Aug 03 10:11:00 GMT 1976

It is also possible to make contrast of time by utilizing the method comparison.
LETS TRY IT
You can try to know your exact age in seconds.

THE CLASS HASH

Hash is an important class. These have similarities with arrays. The slots of this class show different objects. These slots are not in the form of a row.

These are stored in a jumbled up form.

colorArray = [] # same as Array.new
colorHash = {} # same as Hash.new

colorArray[0] = ‘red’
colorArray[1] = ‘green’
colorArray[2] = ‘blue’
colorHash['strings'] = ‘red’
colorHash['numbers'] = ‘green’
colorHash['keywords'] = ‘blue’

colorArray.each do |color|
puts color
end
colorHash.each do |codeType, color|
puts codeType + ‘: ‘ + color
end
red
green
blue
strings: red
keywords: blue
numbers: green

Hashes do not carry objects in a sequence. Hashes do not use 0 and 1 for strings and numbers.
weirdHash = Hash.new

weirdHash[12] = ‘monkeys’
weirdHash[[]] = ‘emptiness’
weirdHash[Time.new] = ‘no time like the present’

ENLARGE CLASSES

It is a great thing that we can write numbers like 23 in English without writing englishNumber 23. Now, we have to type to_eng.
class Integer

def to_eng
if self == 5
english = ‘five’
else
english = ‘fifty-eight’
end

english
end

end

# I’d better test on a couple of numbers…
puts 5.to_eng
puts 58.to_eng
five
fifty-eight

MAKING CLASSES
In Ruby, it is an easy task to build a fresh class. Here, we are going to create a dice:
class Die

def roll
1 + rand(6)
end

end

# Let’s make a couple of dice…
dice = [Die.new, Die.new]

# …and roll them.
dice.each do |die|
puts die.roll
end
3
4

ILLUSTRATIVE VARIABLES

Instance or illustrative variables are like the article of a specific class. These variables works till the object class is in working position. In order to know variables instance from local type variables, @ is used in the start of the name.
class Die

def roll
@numberShowing = 1 + rand(6)
end

def showing
@numberShowing
end

end

die = Die.new
die.roll
puts die.showing
puts die.showing
die.roll
puts die.showing
puts die.showing
1
1
5
5

The roll is used for rolling the dice and number is shown by showing.
class Die

def roll
@numberShowing = 1 + rand(6)
end

def showing
@numberShowing
end

end

# Since I’m not going to use this die again,
# I don’t need to save it in a variable.
puts Die.new.showing
nil

Here, initialize has used in order for setting up the fresh object instantly.
class Die

def initialize
# I’ll just roll the die, though we
# could do something else if we wanted
# to, like setting the die with 6 showing.
roll
end

def roll
@numberShowing = 1 + rand(6)
end

def showing
@numberShowing
end

end

puts Die.new.showing
6

Initialize method is applied whenever a fresh object is made. Now, we are going to create new program. It can be called baby dragon as we are going to make a toy dragon. It can perform some functions like sleep, eat and walk etc.
class Dragon

def initialize name
@name = name
@asleep = false
@stuffInBelly = 10 # He’s full.
@stuffInIntestine = 0 # He doesn’t need to go.

puts @name + ‘ is born.’
end

def feed
puts ‘You feed ‘ + @name + ‘.’
@stuffInBelly = 10
passageOfTime
end

def walk
puts ‘You walk ‘ + @name + ‘.’
@stuffInIntestine = 0
passageOfTime
end

def putToBed
puts ‘You put ‘ + @name + ‘ to bed.’
@asleep = true
3.times do
if @asleep
passageOfTime
end
if @asleep
puts @name + ‘ snores, filling the room with smoke.’
end
end
if @asleep
@asleep = false
puts @name + ‘ wakes up slowly.’
end
end

def toss
puts ‘You toss ‘ + @name + ‘ up into the air.’
puts ‘He giggles, which singes your eyebrows.’
passageOfTime
end

def rock
puts ‘You rock ‘ + @name + ‘ gently.’
@asleep = true
puts ‘He briefly dozes off…’
passageOfTime
if @asleep
@asleep = false
puts ‘…but wakes when you stop.’
end
end

private

# “private” means that the methods defined here are
# methods internal to the object. (You can feed
# your dragon, but you can’t ask him if he’s hungry.)

def hungry?
# Method names can end with “?”.
# Usually, we only do this if the method
# returns true or false, like this:
@stuffInBelly <= 2
end

def poopy?
@stuffInIntestine >= 8
end

def passageOfTime
if @stuffInBelly > 0
# Move food from belly to intestine.
@stuffInBelly = @stuffInBelly – 1
@stuffInIntestine = @stuffInIntestine + 1
else # Our dragon is starving!
if @asleep
@asleep = false
puts ‘He wakes up suddenly!’
end
puts @name + ‘ is starving! In desperation, he ate YOU!’
exit # This quits the program.
end

if @stuffInIntestine >= 10
@stuffInIntestine = 0
puts ‘Whoops! ‘ + @name + ‘ had an accident…’
end

if hungry?
if @asleep
@asleep = false
puts ‘He wakes up suddenly!’
end
puts @name + ‘\’s stomach grumbles…’
end

if poopy?
if @asleep
@asleep = false
puts ‘He wakes up suddenly!’
end
puts @name + ‘ does the potty dance…’
end
end

end

pet = Dragon.new ‘Norbert’
pet.feed
pet.toss
pet.walk
pet.putToBed
pet.rock
pet.putToBed
pet.putToBed
pet.putToBed
pet.putToBed
Norbert is born.
You feed Norbert.
You toss Norbert up into the air.
He giggles, which singes your eyebrows.
You walk Norbert.
You put Norbert to bed.
Norbert snores, filling the room with smoke.
Norbert snores, filling the room with smoke.
Norbert snores, filling the room with smoke.
Norbert wakes up slowly.
You rock Norbert gently.
He briefly dozes off…
…but wakes when you stop.
You put Norbert to bed.
He wakes up suddenly!
Norbert’s stomach grumbles…
You put Norbert to bed.
He wakes up suddenly!
Norbert’s stomach grumbles…
You put Norbert to bed.
He wakes up suddenly!
Norbert’s stomach grumbles…
Norbert does the potty dance…
You put Norbert to bed.
He wakes up suddenly!
Norbert is starving! In desperation, he ate YOU!

In the above mentioned program, we have used some methods which are new for us. The first one is ‘exit’ which ends the program on the spot. The other is ‘private’ which can be used in the mid of the definition of a specific class.

THINGS TO ATTEMPT:

An interesting program can be related to appleTree. You have to make a program which can tell the height of apple tree. When the tree becomes one year old, it height should be more. After the passage of time, it has to bring fruit. You can calculate the figure of apples by counttheapples. You can eat an apple also. Then the total number of apples will be reduced. You can insert a string here. The string can be a warning that you are not allowed to pick more. It can even tell about the taste of the fruit.
You can make classes related to sending or saving a mail, opening a file etc. in short, there is a wide range of classes which can be used for many purposes.

Writing your own methods – Ruby on Rails tutorial

WRITING YOUR OWN METHODS

It is clear that if we would like to repeat something then we can make use of iterators and loops. From time to time, we would like to use a single procedure on changed places in a given program. Here, we are going to mention a list of question which will be asked from different student.
puts ‘Hello, and thank you for taking the time to’
puts ‘help me with this experiment. My experiment’
puts ‘has to do with the way people feel about’
puts ‘Mexican food. Just think about Mexican food’
puts ‘and try to answer every question honestly,’
puts ‘with either a “yes” or a “no”. My experiment’
puts ‘has nothing to do with bed-wetting.’
puts

# We ask these questions, but we ignore their answers.

goodAnswer = false
while (not goodAnswer)
  puts 'Do you like eating tacos?'
  answer = gets.chomp.downcase
  if (answer == 'yes' or answer == 'no')
    goodAnswer = true
  else
    puts 'Please answer "yes" or "no".'
  end
end

goodAnswer = false
while (not goodAnswer)
  puts 'Do you like eating burritos?'
  answer = gets.chomp.downcase
  if (answer == 'yes' or answer == 'no')
    goodAnswer = true
  else
    puts 'Please answer "yes" or "no".'
  end
end

#  We pay attention to *this* answer, though.
goodAnswer = false
while (not goodAnswer)
  puts 'Do you wet the bed?'
  answer = gets.chomp.downcase
  if (answer == 'yes' or answer == 'no')
    goodAnswer = true
    if answer == 'yes'
      wetsBed = true
    else
      wetsBed = false
    end
  else
    puts 'Please answer "yes" or "no".'
  end
end

goodAnswer = false
while (not goodAnswer)
  puts 'Do you like eating chimichangas?'
  answer = gets.chomp.downcase
  if (answer == 'yes' or answer == 'no')
    goodAnswer = true
  else
    puts 'Please answer "yes" or "no".'
  end
end

puts 'Just a few more questions...'

goodAnswer = false
while (not goodAnswer)
  puts 'Do you like eating sopapillas?'
  answer = gets.chomp.downcase
  if (answer == 'yes' or answer == 'no')
    goodAnswer = true
  else
    puts 'Please answer "yes" or "no".'
  end
end

# Ask lots of other questions about Mexican food.

puts
puts ‘DEBRIEFING:’
puts ‘Thank you for taking the time to help with’
puts ‘this experiment. In fact, this experiment’
puts ‘has nothing to do with Mexican food. It is’
puts ‘an experiment about bed-wetting. The Mexican’
puts ‘food was just there to catch you off guard’
puts ‘in the hopes that you would answer more’
puts ‘honestly. Thanks again.’
puts
puts wetsBed
Hello, and thank you for taking the time to
help me with this experiment. My experiment
has to do with the way people feel about
Mexican food. Just think about Mexican food
and try to answer every question honestly,
with either a “yes” or a “no”. My experiment
has nothing to do with bed-wetting.

Do you like eating tacos?
yes
Do you like eating burritos?
yes
Do you wet the bed?
no way!
Please answer “yes” or “no”.
Do you wet the bed?
NO
Do you like eating chimichangas?
yes
Just a few more questions…
Do you like eating sopapillas?
yes

DEBRIEFING:
Thank you for taking the time to help with
this experiment. In fact, this experiment
has nothing to do with Mexican food. It is
an experiment about bed-wetting. The Mexican
food was just there to catch you off guard
in the hopes that you would answer more
honestly. Thanks again.

false
In this program, we have faced the repetition many times. In order to escape from such a position, we make a use of methods.
def sayMoo
puts ‘mooooooo…’
end
The program could not work. Let’s try it again.
def sayMoo
puts ‘mooooooo…’
end

sayMoo
sayMoo
puts ‘coin-coin’
sayMoo
sayMoo
mooooooo…
mooooooo…
coin-coin
mooooooo…
mooooooo…

This attempt is quite well. It is noticeable that methods are mostly related with the objects they are representing.
METHOD LIMITATIONS

The methods to_s, gets and reverse can easily call on a specific object. But the methods like -, +, and puts need parameters for instructing the given object of the way of method.
In order to make addition in the given method, we will do the following steps:
def sayMoo numberOfMoos
puts ‘mooooooo…’*numberOfMoos
end

sayMoo 3
puts ‘oink-oink’
sayMoo # This should give an error because the parameter is missing.
mooooooo…mooooooo…mooooooo…
oink-oink
#
Here, the variable numberofMoos explain the position of the passed parameter.

LOCAL VARIABLES
def doubleThis num
numTimes2 = num*2
puts num.to_s+’ doubled is ‘+numTimes2.to_s
end

doubleThis 44
44 doubled is 88
There are 2 variables num and the other one is numTimes2. Their place is in doubleThis. They are known as local variables. The reason is that their place is within the given method. They can not leave their place.
def doubleThis num
numTimes2 = num*2
puts num.to_s+’ doubled is ‘+numTimes2.to_s
end

doubleThis 44
puts numTimes2.to_s
44 doubled is 88
#>
The local variables can not be replaced by us. It is also important that these variables can not get admission to our variables.
def littlePest var
var = nil
puts ‘HAHA! I ruined your variable!’
end

var = ‘You can\’t even touch my variable!’
littlePest var
puts var
HAHA! I ruined your variable!
You can’t even touch my variable!

HOMECOMING VALUES

There are methods which gives back some value. The arithmetic method gives back numbers whereas string methods give back strings. Now, we are going to look at puts method.
returnVal = puts ‘This puts returned:’
puts returnVal
This puts returned:
nil

It is seen that puts gives back nil value. In order to get string as a returning value, it is needed to use ‘that’ at the ending place.
def sayMoo numberOfMoos
puts ‘mooooooo…’*numberOfMoos
‘yellow submarine’
end

x = sayMoo 2
puts x
mooooooo…mooooooo…
yellow submarine

Now, we are going to rewrite the same psychology test. The answers which have yes value will be taken as true and no will be taken as false.
def ask question
goodAnswer = false
while (not goodAnswer)
puts question
reply = gets.chomp.downcase

if (reply == ‘yes’ or reply == ‘no’)
goodAnswer = true
if reply == ‘yes’
answer = true
else
answer = false
end
else
puts ‘Please answer “yes” or “no”.’
end
end

answer # This is what we return (true or false).
end

puts ‘Hello, and thank you for…’
puts

ask ‘Do you like eating tacos?’ # We ignore this return value.
ask ‘Do you like eating burritos?’
wetsBed = ask ‘Do you wet the bed?’ # We save this return value.
ask ‘Do you like eating chimichangas?’
ask ‘Do you like eating sopapillas?’
ask ‘Do you like eating tamales?’
puts ‘Just a few more questions…’
ask ‘Do you like drinking horchata?’
ask ‘Do you like eating flautas?’

puts
puts ‘DEBRIEFING:’
puts ‘Thank you for…’
puts
puts wetsBed
Hello, and thank you for…

Do you like eating tacos?
yes
Do you like eating burritos?
yes
Do you wet the bed?
no way!
Please answer “yes” or “no”.
Do you wet the bed?
NO
Do you like eating chimichangas?
yes
Do you like eating sopapillas?
yes
Do you like eating tamales?
yes
Just a few more questions…
Do you like drinking horchata?
yes
Do you like eating flautas?
yes

DEBRIEFING:
Thank you for…

false
ANOTHER ILLUSTRATION

We will use another method known as englishNumber. This method will change the number like 23 into twenty three.
def englishNumber number
# We only want numbers from 0-100.
if number < 0
return 'Please enter a number zero or greater.'
end
if number > 100
return ‘Please enter a number 100 or lesser.’
end

numString = ” # This is the string we will return.

# “left” is how much of the number we still have left to write out.
# “write” is the part we are writing out right now.
# write and left… get it? :)
left = number
write = left/100 # How many hundreds left to write out?
left = left – write*100 # Subtract off those hundreds.

if write > 0
return ‘one hundred’
end

write = left/10 # How many tens left to write out?
left = left – write*10 # Subtract off those tens.

if write > 0
if write == 1 # Uh-oh…
# Since we can’t write “tenty-two” instead of “twelve”,
# we have to make a special exception for these.
if left == 0
numString = numString + ‘ten’
elsif left == 1
numString = numString + ‘eleven’
elsif left == 2
numString = numString + ‘twelve’
elsif left == 3
numString = numString + ‘thirteen’
elsif left == 4
numString = numString + ‘fourteen’
elsif left == 5
numString = numString + ‘fifteen’
elsif left == 6
numString = numString + ‘sixteen’
elsif left == 7
numString = numString + ‘seventeen’
elsif left == 8
numString = numString + ‘eighteen’
elsif left == 9
numString = numString + ‘nineteen’
end
# Since we took care of the digit in the ones place already,
# we have nothing left to write.
left = 0
elsif write == 2
numString = numString + ‘twenty’
elsif write == 3
numString = numString + ‘thirty’
elsif write == 4
numString = numString + ‘forty’
elsif write == 5
numString = numString + ‘fifty’
elsif write == 6
numString = numString + ‘sixty’
elsif write == 7
numString = numString + ‘seventy’
elsif write == 8
numString = numString + ‘eighty’
elsif write == 9
numString = numString + ‘ninety’
end

if left > 0
numString = numString + ‘-’
end
end

write = left # How many ones left to write out?
left = 0 # Subtract off those ones.

if write > 0
if write == 1
numString = numString + ‘one’
elsif write == 2
numString = numString + ‘two’
elsif write == 3
numString = numString + ‘three’
elsif write == 4
numString = numString + ‘four’
elsif write == 5
numString = numString + ‘five’
elsif write == 6
numString = numString + ‘six’
elsif write == 7
numString = numString + ‘seven’
elsif write == 8
numString = numString + ‘eight’
elsif write == 9
numString = numString + ‘nine’
end
end

if numString == ”
# The only way “numString” could be empty is if
# “number” is 0.
return ‘zero’
end

# If we got this far, then we had a number somewhere
# in between 0 and 100, so we need to return “numString”.
numString
end

puts englishNumber( 0)
puts englishNumber( 9)
puts englishNumber( 10)
puts englishNumber( 11)
puts englishNumber( 17)
puts englishNumber( 32)
puts englishNumber( 88)
puts englishNumber( 99)
puts englishNumber(100)
zero
nine
ten
eleven
seventeen
thirty-two
eighty-eight
ninety-nine
one hundred

The drawbacks of such programming are that it has a lot of repetitions. It can not be used for numbers which exceeds hundred.
def englishNumber number
if number < 0 # No negative numbers.
return 'Please enter a number that isn\'t negative.'
end
if number == 0
return 'zero'
end

# No more special cases! No more returns!

numString = '' # This is the string we will return.

onesPlace = ['one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine']
tensPlace = ['ten', 'twenty', 'thirty', 'forty', 'fifty',
'sixty', 'seventy', 'eighty', 'ninety']
teenagers = ['eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
'sixteen', 'seventeen', 'eighteen', 'nineteen']

# "left" is how much of the number we still have left to write out.
# "write" is the part we are writing out right now.
# write and left... get it? :)
left = number
write = left/100 # How many hundreds left to write out?
left = left - write*100 # Subtract off those hundreds.

if write > 0
# Now here’s a really sly trick:
hundreds = englishNumber write
numString = numString + hundreds + ‘ hundred’
# That’s called “recursion”. So what did I just do?
# I told this method to call itself, but with “write” instead of
# “number”. Remember that “write” is (at the moment) the number of
# hundreds we have to write out. After we add “hundreds” to “numString”,
# we add the string ‘ hundred’ after it. So, for example, if
# we originally called englishNumber with 1999 (so “number” = 1999),
# then at this point “write” would be 19, and “left” would be 99.
# The laziest thing to do at this point is to have englishNumber
# write out the ‘nineteen’ for us, then we write out ‘ hundred’,
# and then the rest of englishNumber writes out ‘ninety-nine’.

if left > 0
# So we don’t write ‘two hundredfifty-one’…
numString = numString + ‘ ‘
end
end

write = left/10 # How many tens left to write out?
left = left – write*10 # Subtract off those tens.

if write > 0
if ((write == 1) and (left > 0))
# Since we can’t write “tenty-two” instead of “twelve”,
# we have to make a special exception for these.
numString = numString + teenagers[left-1]
# The “-1″ is because teenagers[3] is ‘fourteen’, not ‘thirteen’.

# Since we took care of the digit in the ones place already,
# we have nothing left to write.
left = 0
else
numString = numString + tensPlace[write-1]
# The “-1″ is because tensPlace[3] is ‘forty’, not ‘thirty’.
end

if left > 0
# So we don’t write ‘sixtyfour’…
numString = numString + ‘-’
end
end

write = left # How many ones left to write out?
left = 0 # Subtract off those ones.

if write > 0
numString = numString + onesPlace[write-1]
# The “-1″ is because onesPlace[3] is ‘four’, not ‘three’.
end

# Now we just return “numString”…
numString
end

puts englishNumber( 0)
puts englishNumber( 9)
puts englishNumber( 10)
puts englishNumber( 11)
puts englishNumber( 17)
puts englishNumber( 32)
puts englishNumber( 88)
puts englishNumber( 99)
puts englishNumber(100)
puts englishNumber(101)
puts englishNumber(234)
puts englishNumber(3211)
puts englishNumber(999999)
puts englishNumber(1000000000000)
zero
nine
ten
eleven
seventeen
thirty-two
eighty-eight
ninety-nine
one hundred
one hundred one
two hundred thirty-four
thirty-two hundred eleven
ninety-nine hundred ninety-nine hundred ninety-nine
one hundred hundred hundred hundred hundred hundred
MAKE ATTEMPTS
Now, make a program which will give back the value two thousand as an alternative of twenty hundred.
Now, make a program which will give back the value two million as an alternative of two thousand thousand.

Arrays and Iteratiors – Ruby on Rails tutorial

ARRAYS AND ITERATORS

Array proceeds like a list of variables. Each and every one in the lists can perform a different function.
[]
[6]
['Hi', Bye']

taste = ‘strawberry’ # This is not an array, of course…
[89.9, flavor, [true, false]] # …but this is.
In the start, array in unfilled then the next array has one digit. The third array has 2 strings. We have given index numbers, so that we can easily find out the thing we desire to get from an array. Most of the time, the primary slot is taken as zero.
names = ['Adala', 'Bell', 'Charle']

puts names
puts names[0]
puts names[1]
puts names[2]
puts names[3] # This is out of range.
Adala
Bell
Charle
Ada
Bell
Charle
nil

It is clear that puts names[0] is used to show the very first name and the puts names[1] is used to write the 2nd name.
.
Now it is making confusion that what is present in the 3rd slot. Here, nil is used to refer nothing. In order to escape from such confusion, we use methods.
THE METHOD EACH
The method ‘each’ is used to make some change in the referred objects.
languages = ['English', 'German', 'Ruby']

languages.each do |lang|
puts ‘I love ‘ + lang + ‘!’
puts ‘Don\’t you?’
end

puts ‘And let\’s hear it for C++!’
puts ‘…’
I love English!
Don’t you?
I love German!
Don’t you?
I love Ruby!
Don’t you?
And let’s hear it for C++!

Each is specific type of method which functions like a loop. That’s why it is known as iterators. It is important to know that iterators have ‘do—-end’.
Now, we are going to use a method which is integer based.
3.times do
puts ‘Hip-Hip-Hooray!’
end
Hip-Hip-Hooray!
Hip-Hip-Hooray!
Hip-Hip-Hooray!
SUPPLEMENTARY ARRAY METHODS
Now, we are going to handle to join and to_s. The function of to_s is same like join but the divergence is that join includes string in the mid of the object of a specific array.
foods = ['artichoke', 'brioche', 'caramel']

puts foods
puts
puts foods.to_s
puts
puts foods.join(‘, ‘)
puts
puts foods.join(‘ :) ‘) + ‘ 8)’

200.times do
puts []
end
artichoke
brioche
caramel

artichokebriochecaramel

artichoke, brioche, caramel

artichoke :) brioche :) caramel 8)

The function of puts is not similar to others. For all the object of a given array, it calls the puts.
favorites = []
favorites.push ‘raindrops on roses’
favorites.push ‘whiskey on kittens’

puts favorites[0]
puts favorites.last
puts favorites.length

puts favorites.pop
puts favorites
puts favorites.length
raindrops on roses
whiskey on kittens
2
whiskey on kittens
raindrops on roses
1

LITTLE TO ATTEMPT
Attempt to write the upper mentioned program and try to avoid the use of sort.

Flow control – Ruby on Rails tutorial

FLOW CONTROL
EVALUATION METHODS
In case, our object is smaller than or greater than any other object then we use <, >symbols.
puts 3 > 2
puts 4 < 3
true
false
Sometimes, object is smaller then or equal to any other object then the symbol will be <=.
puts 6 >= 6
puts 3 <= 4
true
false
Here, == wants to ask question that these are similar or not? Similarly, the symbol != asks that these are different or not?
puts 2 == 1
puts 3 != 1
false
true
For make comparison among different strings, we use alphabetical order.
puts 'cow' < 'duck'
true
But in computer, capital words come earlier than the smaller words. So, it is important to write words either in upcase or downcase.

BRANCHING
puts 'Hey, where are you going?'
name = gets.chomp
puts 'Hi, ' + name + '.'
if name == 'Clifton'
puts 'What a place!'
end
Hey, where are you going?
Clifton
Hi, Clifton.
What a place!
Now, we are going to use a new name:
Hey, where are you going?
Chgjgjgvgc
Hi, Chgjgjgvgc
.
In branching, the code will be executed when if statement will be true. Otherwise, it will not work.
puts 'I can guess about your future just by knowing your name:'
name = gets.chomp
if name == 'Charles'
puts 'You will get many opportunities in coming years.'
else
puts 'There are many other things!'
puts 'But I don’t have time now!'
end
I can guess about your future just by knowing your name:
Charles
You will get many opportunities in coming years.
Here, we are going to use a new name:
I can guess about your future just by knowing your name:
Romeo
There are many other things!
But I don’t have time now!

It is like a tree which has many branches and these branches also have more branches.
puts 'Hi, I am John.'
puts '. Please introduce yourself!'
name = gets.chomp

if name == name.capitalize
puts 'Have a seat, ' + name + '.'
else
puts name + '? Are you saying ' + name.capitalize + ', isn’t it?'
puts 'Strange you don’t know the spelling of your name!'
reply = gets.chomp

if reply.downcase == 'yes'
puts 'Ok! Have a seat!'
else
puts 'You can go now!'
end
end
Hi, I am John.
Please introduce yourself
chales
charles? Are you saying Charles, isn’t it?
Strange you don’t know the spelling of your name!
yeah
Ok! Have a seat!
Now, we will use capitalization:
Hi, I am John.
Please introduce yourself
Charles
Have a seat, Charles.
It is much better to write if and end simultaneously. Otherwise, we can face trouble.
puts Hi, I am John.
Puts Please introduce yourself

name = gets.chomp

if name == name.capitalize
else
end
After writing if and end, we can write the whole programming.
puts ' Hi, I am John.
Puts Please introduce yourself

name = gets.chomp

if name == name.capitalize
# She's civil.
else
# She gets mad.
end
It is important to know that the things written subsequent to a are taken as comment.
puts ' Hi, I am John.
Puts Please introduce yourself

name = gets.chomp

if name == name.capitalize
puts 'Have a seat, ' + name + '.'
else
puts name + '? Are you saying ' + name.capitalize + ', isn’t it?'
puts Strange you don’t know the spelling of your name!

reply = gets.chomp

if reply.downcase == 'yes'
else
end
end
LOOPING

Looping is a process through which you can do a thing again and again. You have to define a condition for making a stop.
command = ''

while command != 'bye'
puts command
command = gets.chomp
end

puts 'Come again soon!'

Hello?
Hello?
Hi!
Hi!
Nice to meet you
Nice to meet you.
Oh... how sweet!
Oh... how sweet!
Bye
Come again soon!

SOME LOGICAL POINTS:
It is also necessary that this program should admire the name of everyone.
puts 'Hello, what\'s your name?'
name = gets.chomp
puts 'Hello, ' + name + '.'
if name == 'Chris'
puts 'What a lovely name!'
else
if name == 'Katy'
puts 'What a lovely name!'
end
end
Hello, what's your name?
Katy
Hello, Katy.
What a lovely name!
When we ask the program to rewrite the same word or sentence then it will not go against the program.
puts 'Hello, what\'s your name?'
name = gets.chomp
puts 'Hello, ' + name + '.'
if (name == 'Chris' or name == 'Katy')
puts 'What a lovely name!'
end
Hello, what's your name?
Katy
Hello, Katy.
What a lovely name!
The best option is to use logical operators with () parenthesis.
iAmChris = true
iAmPurple = false
iLikeFood = true
iEatRocks = false

puts (iAmChris and iLikeFood)
puts (iLikeFood and iEatRocks)
puts (iAmPurple and iLikeFood)
puts (iAmPurple and iEatRocks)
puts
puts (iAmChris or iLikeFood)
puts (iLikeFood or iEatRocks)
puts (iAmPurple or iLikeFood)
puts (iAmPurple or iEatRocks)
puts
puts (not iAmPurple)
puts (not iAmChris )
true
false
false
false

true
true
true
false

true
false

TRY TO ATTEMPT:

You can make a program in which the listener is a deaf. He can not understand what you are saying. Each time, he is going to say speak louder!