You are on page 1of 14

Lesson - 1

Introduction to Ruby
A dynamic, open source programming language with a focus on simplicity
and productivity. It has an elegant syntax that is natural to read and easy to
write. Ruby is also an object oriented language.

Installation

Installation on Windows
Installation on Mac

Installation on Windows:
To download Ruby, go to rubyinstaller.org/downloads
Download the latest version of Ruby. The one which is in the top most.
For 64 bit Operating Systems, download installer that end with (x64).
After downloading the exe file, double click to open the file.
Choose the language.

Click I accept the License.

Browse and select the desired installation path you want. But it is
recommended to install on the default directory. And Check the 3 options below

Install Td/k support

Add Ruby executables to your PATH

Associate .rb and .rbw files with Ruby installation

And click Install

You will see the installation of ruby in following screen.

Finally click Finish.

Installation on Mac:
Ruby has already installed on Macintosh.
So dont need to go through installation procedures.

Using the Ruby Interactive Shell:


It is also called as irb.
It allows us to type ruby expressions or statements.
Open the command prompt and type irb. (both Windows and Macintosh)

As you can see in the above screen, we can write ruby expressions and
statements.
The texts entered within quotes are called as String.
We can perform concatenation operation with two strings.
We can store the value to the variable like
name = Welcome to Ruby!!!
Ruby is a case sensitive programming language. So, name is different
from Name and NAME is different from both.
We can also perform some complicated operations. See the below screens.

This statements prints 1 to 9.

Whoa!! What just had happened? You might be confused after seeing this.
I said it prints 1 to 9. But its showing all 1s that too many. To get out of this,
press Ctrl + C
This is because the variable i is not incremented.
The following code prints from 1 to 9
i=1
while i < 10
print i

i += 1
end
This code prints from 1 to 9.
We can also define functions in irb.
A function is a set of statement(s) to perform a particular task.
Here is a function that performs square of a number.
def square(n)
return n * n
end
Calling the function: square(4)
After calling this function by passing 4 as argument, it returns 16 by
performing the operation 4 * 4.
Likewise, a function to find the area of a circle.
def circle(radius)
return radius * radius * 3.14
end
Calling the function: circle (5) by passing the argument as 5.
This function returns 78.5 by multiplying 5 * 5 * 3.14

Ruby Scripts
We are going to run ruby from a text editor rather that a Command
Prompt.
You can use any text editor like Notepad or Notepad++.
Ruby scripts have .rb extension. So, you have to save the file with the
extension .rb
Now, in your editor enter the following code and save it with any name
with .rb extension:
puts Welcome to Ruby!!!
Im saving this as first.rb. To run the program, go to Command Prompt,
and type ruby first.rb without quotes.
You can actually run by simply typing first.rb, because during installation,
you have checked Add Ruby executables to your PATH. So, its enough to type
first.rb for running the program.

Likewise, you can use any text editor in Macintosh and follow the same
procedures as in Windows.

Lesson - 2
Displaying Data
Now, we can see how to display data to the screen.
To display text, we have two functions
puts()
print()

puts adds a new line automatically to the data.


puts ("hello, world")
puts "hello, world"
You can use both the ways to display the data.
puts "hello, world", "Goodbye, world"

puts "practice", "makes", "a", "man", "perfect"

print doesnt adds a new line.


print "hello, world"
If you want to include new line at the end of the data using print method,
then you have to include special character \n

print "hello, world\n"


print "practice\n", "makes\n", "a\n", "man\n", "perfect\n"

You can also display the numeric data using these functions.
puts(1)
print(1)
Also you can evaluate the expression and display the result.
puts (2+2)
print(2+2)

Getting Data
To make the program to interact with user, we have to get the input data
from the users.
To do this, we can use gets() method.
gets() function gets input from the keyboard in string format and stores
the value in the variables.
name = gets
This statement gets a string input from the user and stores it in the
variable called name.
It also appends a \n new line character at the end of the input entered by
the user.

So, when you type the variable name, it displays what it is stored in it.
When you display using print function, it displays the text entered by the
user along with a new line.
If you want to remove the newline, you can use a function called chomp
The following statement removes the newline from the input entered by
the user.
print name.chomp
The following code performs addition of two whole numbers with the
numbers you have got from the user:
number1 = gets
number 2 = gets
(Integer)number1 + Integer(number2)
Integer() part of the code looks tricky for you now.
As said before gets method gets input in string format. So, you have to
convert it to whole number. This can be done using Integer() function.

If you dont convert those variables into integer and when you try to
perform addition, it concatenates two string. Do you remember concatenating
two strings which we have seen earlier in Chapter 1?
Likewise, to add two decimal numbers, look the following code:
num1 = gets
num2 = gets
Float(num1) + Float(num2)
Float() method is used to convert data into decimal format. If the
conversion is not done, it simply performs the concatenation operation as said
before.

Lesson 3
Data types
In this lesson, we are about to see different data types.

String data type


Lets start with string datatype.
Strings can be formed in ruby using single quotes or double quotes.
But ruby treats string with double quotes.
Any characters such as number or alphabets or symbols enclosed within
quotes are Strings.

Another way to create string is using gets method, which we have seen in
last chapter.
As you already know, using gets it automatically inserts new line at the
end.

Likewise, other characters can also be embedded in strings other than


newline.
name = Bharath\tKumar
\t adds tab space
\s adds space
For creating strings, there is an added advantage of using double quotes
over single quotes.
If you use double quotes, you could use single quote as apostrophe in the
string.
str = Bharaths
But you cannot use single quote inside single quotes.
But, still there is a way to do so, using a special character like \t and \s.
str = Bharath\s
\ to include apostrophe in string.
In the below image, when using single quote inside single quotes you can
see that we cant able quit the interactive mode. So, its not advisable.

HERE:
To create a multiline string and store it in a variable HERE keyword is
used.

This begins with a two less than symbols << and the keyword HERE
indicates that, until you see the keyword HERE again, store all the values in the
variable.

quote = << HERE


What you do
today can
improve
all your
tomorrows
HERE
So, the value What you do\ntoday can\nimprove\nall your\ntomorrows is
stored in the variable quote.
This is the easy way to store large fragments of text in the variable.
Split method:
Split is useful method for taking the string and splitting into parts.

first,last = Bharath,Kumar.split(/,/)
Here , is the delimiter. We use slashes (/) to delimit the delimiters.

When this statement is executed, the piece of text before comma (,) is
assigned to the variable first and the piece of text after comma (,) is assigned
to the variable last.
Therefore, value Bharath is assigned to the variable first and value
Kumar is assigned to the variable last.
Squeeze method:
Squeeze is used to remove trailing spaces from the string.

In the above image, you could note the number of spaces in the variable
first.
When printing the first variable using squeeze method it removes the
trailing spaces.

Number data type


In this lessons, we are going to work with numbers data type.
Ruby supports major number systems such as whole numbers, floating
point numbers.
Different bases such as Binary, Octal and Hexadecimal are allowed.

To write in binary we use 0b and the corresponding number. For example 5


can be written as 101 in binary.
Likewise, to represent number in hexadecimal 0x is used and for octal 0
alone is used.
Negative numbers are represented by using unary operator (minus)
before the number.
Ruby supports different arithmetic operations such as addition,
subtraction, multiplication, division, modulus and exponentiation.

In above image, you could see the arithmetic operations performed.


9 % 3 this statement leaves the remainder when 3 divided by 9.
2 ** 5 this statement raises 2 to the power of 5.
So, the result will be 2 * 2 * 2 * 2 * 2 is equal to 32.
ABS:
abs is a method used to find the absolute value of a number.
For example, -26.abs gives the value of 26.
Some other methods are div and modulo.

You can also convert numbers to strings.


For example, to convert 100 into a string
100.to_s

Boolean data type


Boolean type variables can hold two values true or false. But in ruby, it
can also hold third type of value in Boolean variable called nil.
But in most context, we work with only true and false values. So, lets
concentrate on those two.

You might also like