Ruby

Ruby is a pure object oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan.
Ruby is "A Programmer's Best Friend".
Features of Ruby
Ruby is a server side programming language.
Ruby is an interpreted language i.e executed line by line during execution rather than compiled.
It is a platform dependent because it runs various platforms.
By using ruby we can develop internet and intranet applications.
Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase.
Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts.
Scalable and big programs written in Ruby are easily maintainable.
It is easy to read, comprehend, and work in because it’s close to a natural language.
Installation Steps:
1.First open any browser and type ruby installer download it from there.
Download any of the above version, best go with latest version because it will provide all latest features than earlier versions.
2. After download is completed double click on it . It shows you the following window.
Click on I accept the license agreement and then click on next.
3. The following window will be opened.
Select all the three options it will automatically sets the path for the ruby . No need to set path separately and then click on Install.
4. 
Click on Next button.
5. It will extract all the files.
6. After extracting of files completed then a new window will be displayed.
Click on the Finish button.
Basic Syntax:
1.Printing the output using Print: 
Print “ Data to print ”
Eg: 
Here in the above program irb means interactive ruby, 001 means first line of the code and nil means no errors in the program.
2. Printing the output using Puts:
Puts “Data to print”
Sample Program using Edit Plus Editor:
When you write programs using edit plus editor we have to save the file with .rb extension.
Syntax to execute .rb file in command prompt
  • Ruby filename.rb
Output:
Sample program for looping:
Here in the above case we are not getting the space between the iterations. For getting space use \n.
  • There is no problem with end statement if we give in the same line or in next line for that look at the following example
  • Basic arithmetic operations using interactive ruby
  • If any of the value is floating point literal then output is floating point
Eg:
Rules for writing variables:
  • The variable name could any character 
  • Don’t start the variables name with digits.
  • You can use the digits at the end.
  • There is no character space is allowed.
  • We can use _(underscore) symbol.
  • It is a case sensitive.
Examples for above rules
  • Data = 20 it will be accepted
  • My Number = 20 not accepted.
  • _data = 20 it will be accepted.
  • 3x = 20 not accepted.
  • data$%=20 not accepted.
  • Data123=20 it will  be accepted.
Ruby Comments
1.Single line comments: For commenting single lines we use # symbol.
Eg:


2. Multiline comments: This is for commenting multi lines for this we use BEGIN and END statements.
Eg:
Output:


1.Begin and End statements:
The begin statement always executes first and the end statement executes at the last irrespective of their positions in the
program.
Eg:
Output:


Changing the order:
Output:


2.How to take user inputs in ruby
Eg: For string type
Output:
Eg: For Integer types
Output:


Eg: For floating points 
Output:
Gets by using chomp 
Output:


3.Difference between gets and gets.chomp
While taking user inputs if we use only gets then it will store extra character \n . But when we use gets.chomp then it doesn't store
any extra character.  You will get clarity about this by the following example.
Eg:
Output:


Output:
4. Classes and Objects
Class is a user defined datatype wrapping up data and methods as a single unit. It is a blueprint of the object we can create
any number of objects using class. Physically it does not exist in the world. To implement object-oriented programming by using
Ruby, you need to first learn how to create objects and classes in Ruby.
Eg: Fruit , Car, Pen
A class in the ruby always start with keyword class followed by the class name. The name should always be in initial capitals. The
class Customer can be displayed as −
class Customer
end
You terminate a class by using the keyword end. All the data members in the class are between the class definition and the end keyword.
  • Object is nothing but an instance of a class it physically exists in the real word entity 
Eg: Mango, Ferrari, Montex


Creating Objects in Ruby using new Method
Here is the example to create two objects cust1 and cust2 of the class Customer −
Cust1 = Customer.new
Cust2 = Customer.new
Here, cust1 and cust2 are the names of two objects. You write the object name followed by the equal sign (=) after which the class
name will follow. Then, the dot operator and the keyword new will follow.
5. How to create methods in ruby
Syntax:
Class Sample
  def function
    Statement1
    Statement2
   end
end
For methods def and end statements will be there and methods will be called directly by method names see the following
example.
Example:
Output:


Ruby return statements: The return statement in ruby is used to return one or more values from a ruby method.
Eg:
Output:
Variable number of Parameters: Suppose you declare a method that takes two parameters, whenever you call this method, you need to pass two parameters along
with it. Ruby allows you to declare methods that works with
variable number of parameters.
Eg:
Output:
Ruby undef statement: This cancels the method definition. 
6.Types of variables
Variables are the memory locations, which holds any data to be used by any program.
There are five types of variables supported by Ruby. You already have gone through a small description of these variables in the
previous chapter as well. These five types of variables are explained in this chapter.
1.Global variables: Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with
the -w option.
Note: In Ruby, you CAN access the value of any variable or constant by putting a hash (#) character just before that
variable or constant.
Output:
2.Instance variables: Instance variables begin with @. Uninitialized instance variables have the value nil and produce
warnings with the -w option.
Output:
3.Class Variables: Class variables begin with @@ and must be initialized before they can be used in method definitions.
4.Local Variables: Local variables are the variables that are defined in a method. Local variables are not available outside the
method. 


7. Operators: 
Output:
Output:


8.Ruby if...else Statement

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.
Output:

9.Ruby unless Statement

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.
Output:

Ruby case Statement

case expression
[when expression [, expression ...] [then]
   code ]...
[else
   code ]
end
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.
Output:


16/10/2019


Ruby Loops: Loops are used to execute the same block of code a specified number of times.
1.While loop:
Syntax:
while conditional [do]
          code
end
A while loop's conditional is separated from code by the reserved word do, a newline, backslash \, or a semicolon ;.
Output:
2.Ruby while modifier: If a while modifier follows a begin statement with no rescue or ensure clauses, code is executed once before the conditional is evaluated.
Syntax:
Begin 
Code
End while conditional
Eg:
Output:
3. Ruby until statement: Executes code while conditional is false.
Syntax:
Until conditional [do]
Code
End
Eg:
Output:
4. Ruby until modifier: If an until modifier follows a begin statement with no rescue or ensure clauses, code is executed once before
the condition is evaluated.
Syntax:
Begin
Code 
End until conditional
Eg:
Output:
Ruby for statement: Executes code once for each element in expression.
Syntax:
For variable [, variable…..] in expression [do]
Code 
End
Eg:
Output:
Ruby break statement: Terminates the most internal loop. Terminates a method with an associated block if called within the block
(with the method returning nil).
Syntax:
Break
Eg:
Output:
Ruby next statement: Jumps to the next iteration of the most internal loop. Terminates execution of a block if called within a block.
Eg:


Output:
Ruby redo statement: Restarts this iteration of the most internal loop, without checking loop condition.
Syntax:
Redo
Eg:
This will provide an infinite loop.
String related features of ruby:
Expression Substitution: Expression substitution is a means of embedding the value of any Ruby expression into a string using #{ and } −
Eg:
Output:
String Built-in methods:
We need to have an instance of String object to call a String method. Following is the way to create an instance of String object −
new [String.new(str = "")]


This will return a new string object containing a copy of str. Now, using str object, we can all use any available instance methods.
Eg:
Output:
10.Arrays:
Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by
an index.
Array indexing starts at 0, as in C or Java. A negative index is assumed relative to the end of the array --- that is, an index of -1
indicates the last element of the array, -2 is the next to last element in the array, and so on.
Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, even other Array objects. Ruby arrays are not as rigid
as arrays in other languages. Ruby arrays grow automatically while adding elements to them.
Creating array: There are many ways to create an array one of them is by using new class method.
names= Array.new
Another way to create an array
names=Array[1,2,3]


1.You can set the array size at the time of array creation like below.
names= Array.new(15)
The array names now has a size or length of 15 elements. You can return the size of an array with size or length methods.
Output:
2.You can assign a value to each element in the array as follows.
Output:
3.You can also use a block with new, populating each element with what the block evaluates to.
Output:
Array Built-in methods: We need to have an instance of Array object to call an Array method. 
Output:
11.Hashes: Similar to array, Hashes are heterogeneous i.e it can had mixture of datatypes in the same hash. Hashes contains values in the
form of key and value as a pair.
There are three ways to create hashes
Syntax:
hash_name={“key”=>”value”}
Here the can be anything like string, float, integer.
Eg:
Output:
To print only key:
Eg:
Output:
To print only value:
Output:
Printing using loops:
Output:
How to invert values to keys and keys to values: By using invert statement we can convert values to keys and keys to values and vice versa.
Eg:
Output:
Second way of creating hash:
Syntax:
hash_name= Hash.new
hash_name[“key1”]=”value1”
hash_name[“key2”]=”value2”
hash_name[“key3”]=”value3”
Eg:
Output:
To print particular value by using key names
Output:


How to check whether the key is avail or not 
There are several ways to check the key is present or not in the data
1.puts hash_name.has_key?(“key”)
2.puts hash_name.key?(“key”)
3.puts hash_name.include?(“key”)
Eg: It returns true or false.
Output:
How to check whether value is available or not 
There are several ways to check the value is present or not in the data
1.puts hash_name.has_value?(“value”)
2.puts hash_name.value?(“value”)
3.puts hash_name.include?(“value”)
Eg:


Output:
17/10/2019
-----------------------
How to duplicate the hashes
Syntax:
new hashname= existing hash name.dup
Output:
To check new hash and existing hashes are equal or not
Output:
How to clear all the data in new hash
Syntax:
new hashname.clear


Output:
Ways to delete the pairs from hashes
1. hashname.delete(“key”) 
Eg:
Output:
Note:In the above case instead of key if we give value then it won’t delete the data from the hash.
2.hashname.shift
It deletes the first pair in hash.
Eg:
Output:
3.hashname.delete_if(|key,value| key == “key name”)


Eg:
Output:


In the above case we can delete the pair by using value in the place of key.


Another way of creating hash and inserting key and values
Eg:


Output:
Merge function in Ruby: It merges the two hashes together.
Eg:


Output:
Merge with exclamation(!):
Eg:
Output:
Update function: Update and merge with exclamation both are synonyms.
Eg:
Output:
Assoc function: It returns nil or key value pair. In this case we have to give the key name only, otherwise it will return
nil value.
Eg1:
Output:
Eg2:
Output:
Rassoc function: It returns nil or key value pair. In this case we have to give the value name only, otherwise it will
return nil value.
Eg1:
Output:
Eg:
Output:
Ruby Dates and Time:
There are three classes are present in ruby to get the time and dates. They are
1.Time class
2.Date class
3.DateTime calss
Ways to get time and date using time class
Syntax:
Time.new(yyyy,mm,dd,hour,min,sec,’time zone’)
Eg1:
Output:
Eg2:
Output:
Eg3:
Output:
Eg4: In this case the date sets to january first.
Output:
To get the present date and time
Output:

Various ways to initialize the time object
Output:

To check day
Output:

To check which day it is. It returns true or false
Output:


To store the date and time in array
Output:

To display the forward date and time
Output:

Displaying date by using date class
Syntax:
Date.new(yyyy,mm,dd) 
In date class we have to use date file which is already exists in ruby library otherwise we don’t get the output.
Output:

Displaying forward date by using date class
Output:

Displaying date and time by using datetime class
Output:
Time formatting directives
%a The abbreviated weekday name (Sun).
%A The full weekday name (Sunday).
%b The abbreviated month name (Jan).
%B The full month name (January).
%c The preferred local date and time representation.
%d Day of the month (01 to 31).
%H Hour of the day, 24-hour clock (00 to 23).
%I Hour of the day, 12-hour clock (01 to 12).
%j Day of the year (001 to 366).
%m Month of the year (01 to 12).
%M Minute of the hour (00 to 59).
%p Meridian indicator (AM or PM).
%S Second of the minute (00 to 60).
%U Week number of the current year, starting with the first Sunday as the first day of the first week (00 to 53).
%w Day of the week (Sunday is 0, 0 to 6).
%x Preferred representation for the date alone, no time.
%X Preferred representation for the time alone, no date.
%y Year without a century (00 to 99).
%Y Year with century.
%Z Time zone name.
Eg:
Output:
Ranges: Ranges occur everywhere: January to December, 0 to 9, lines 50 through 67, and so on. Ruby supports ranges
and allows us to use ranges in a variety of ways −
1.Ranges as sequences
2.Ranges as conditions
3.Ranges as intervals
Ranges as sequences: Ruby creates these sequences 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.
(1..5) => 1,2,3,4,5
(1...5) => 1,2,3,4
Eg:
Output:
Ranges as conditions:Ranges may also be used as conditional expressions. For example, the following code fragment
prints sets of lines from the standard input, where the first line in each set contains the word start and the last line the word ends
While gets
Print if /start/../end/
End
Output:
Ranges as intervals:
A final use of the versatile range is as an interval test: seeing if some value falls within the interval represented by the range.
This is done using ===, the case equality operator.
Output:
Iterators:Iterators are nothing but methods supported by the collections.Objects that stores a group of data members are called
collections.In ruby arrays and hashes termed as collections.
Iterators return all the elements of a collection, one after the other. We will be discussing two iterators here, each and collect. Let's look at these in detail.
Ruby each Iterator: The each iterator returns all the elements of an array or a hash.
Syntax:
Collection.each do |variable|
Code 
End
Executes code for each element in the collection. Here, collection could be an array or a ruby hash.
Output:
Ruby collect iterator: The collect iterator returns all the elements of a collection.
Syntax:
collection=collection.collect
Output:
File I/O: The class IO provides all the basic methods, such as read, write, gets, puts, readline, getc, and printf.
The puts statement: The puts statement is used to print the statement on the screen.
Eg:
Output:
The gets statement: The gets statement is used to take the user inputs.
Eg:
Output:
The putc statement:The putc statement is used to print one character at a time on the screen.
Eg:
Output:
The print statement:
The print statement is similar like puts statement, the difference is the puts statement enters into the new line after
printing where as in print statement the cursor will be in the same line position.
Eg:
Output:
Reading and writing into a file:
You have to use the syswrite method to write data into the file and you have to use the sysread method to read the data
from the file.
Output:



18/10/2019
---------------------
12.The IO.readlines method: The class File is a subclass of the class IO. The class IO also has some methods, which can be used to manipulate files.
One of the IO class methods is IO.readlines. This method returns the contents of the file line by line. The following code displays the use of the method IO.readlines
Eg:
Output:
The IO.foreach method: This method also returns output line by line. The difference between the method foreach and the method readlines is that the method foreach is associated with a block. However, unlike the method readlines, the method foreach does not return an array. For example −
Eg:
Output:
13.Exceptions: The execution and the exception always go together. If you are opening a file, which does not exist, then if you did not handle
this situation properly, then your program is considered to be of bad quality.
The program stops if an exception occurs. So exceptions are used to handle various type of errors, which may occur during a
program execution and take appropriate action instead of halting program completely.
Ruby provides a nice mechanism to handle exceptions. We enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.


Syntax:
Begin
#-
Rescue oneTypeOfException
#-
Rescue anotherTypeOfException
#-
Else
Another exceptions
Ensure
# will be executed always
End
Eg:
Output:
Retry statement: You can capture an exception using rescue block and then use retry statement to execute begin block from the beginning.
Ensure statement: Sometimes, you need to guarantee that some processing is done at the end of a block of code, regardless of whether an
exception was raised.
Output:
Programs:
  1. Write a program for finding first non-repeated characters in the given string
Code:
Output:
  1. Write a program for finding permutations of a given string
Code: Direct method
Output:
Normal method:
Output:
  1. Write a program for finding "Replacing the first highest repeated character with user given character".
Output:



Comments