0% found this document useful (0 votes)
653 views

Ruby PDF

The document provides an overview of the Ruby programming language. It discusses that Ruby is a dynamic, open source, object-oriented programming language that can run on various platforms like Windows, Mac OS, and UNIX. It also emphasizes that Ruby code follows an object-oriented approach where every element is an object that has properties and methods. The document then discusses Ruby's history, features, applications, differences from Java, installation process, classes/objects concept, variables, operators, comments, and conditional statements like if/else, case, unless.

Uploaded by

Rami Munawir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
653 views

Ruby PDF

The document provides an overview of the Ruby programming language. It discusses that Ruby is a dynamic, open source, object-oriented programming language that can run on various platforms like Windows, Mac OS, and UNIX. It also emphasizes that Ruby code follows an object-oriented approach where every element is an object that has properties and methods. The document then discusses Ruby's history, features, applications, differences from Java, installation process, classes/objects concept, variables, operators, comments, and conditional statements like if/else, case, unless.

Uploaded by

Rami Munawir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

RUBY

PROGRAMMING
LANGUAGE
INTRODUCTION
Ruby is a dynamic, open source, object oriented and reflective programming
language.

It runs on all types of platforms like Windows, Mac OS and all versions of
UNIX.

It is fully object oriented programming language.

Each and every code has their properties and actions. Here properties refer to
variables and actions refer to methods.

Ruby is considered to follow the principle of POLA (principle of least


astonishment). It means that the language behaves in such a way to minimize
the confusion for experienced users.
HISTORY
Ruby was created by Yukihiro Matsumoto, or "Matz", in
Japan in the mid 1990's.
It was designed for programmer productivity with the idea that
programming should be fun for programmers.

It emphasizes the necessity for software to be understood by


humans first and computers second.

Ruby continues to gain popularity for its use in web application


development.

Ruby has a vibrant community that is supportive for beginners and


enthusiastic about producing high-quality code.
The Ruby on Rails framework, built with the Ruby language by David
Heinemeier Hansson, introduced many people to the joys of programming
in Ruby.
FEATURES
Ruby language has many features.

Object-oriented

Flexibility

Mixins

Visual appearance

Dynamic typing

Keywords

Statement delimiters
(Continuation)
FEATURES
Variable constants

Naming conventions

Method names

Singleton methods

Missing method

Case Sensitive
APPLICATIONS
KwikiMove – on-demand moving service

HelloCare – everyday helpers services marketplace with Ruby on

Rails

Wecam – marketplace to buy and sell video production

Senden24 – 1 hour delivery MVP marketplace development

Shipwise – MVP development project for multi modal shipments

management platform

UKRAVIT: CRM for agro business company


Woobra – marketplace for product sourcing

Movinga – online home removals

VYDA – video screen casts live sharing social network

Less Accounting – business accounting SaaS

Hotel Cloud – e-concierge mobile apps

GradReady – educational SaaS development


WHY RUBY????

Write Less Code


Here’s the classic “Hello, world” example in Java:

public class HelloWorld


{
public static void main(String[] args)
{
System.out.println("Hello, world");
}
}
(Continuation)

Now, here’s a single line of Ruby code that does the same thing:

puts "Hello, world"

Here’s a list of symbols you’d have to understand in order to write


the Java sample:
public, class, {}, static, void, main, (), String[], System.out, println, ;
(Continuation)

Useful Features
This code:

puts("delta alpha victor mike sierra".split.sort.map{|word|


word.capitalize})

Produces this output:

Alpha
Delta
Mike
Sierra
Victor
RUBY V/S JAVA
(Continuation)
DIFFERENCE
•You don’t need to compile your code. You just run it directly.

•You use the end keyword after defining things like classes, instead of having to
put braces around blocks of code.

•You have require instead of import.

•All member variables are private. From the outside, you access everything via
methods.

•Parentheses in method calls are usually optional and often omitted.

•Everything is an object, including numbers like 2 and 3.14159.

•Variable names are just labels. They don’t have a type associated with them.
•There are no type declarations. You just assign to new variable
names as-needed and they just “spring up” (i.e. a = [1,2,3] rather
than int[] a = {1,2,3};).

•The constructor is always named “initialize” instead of the name of


the class.

•You have “mixins” instead of interfaces.

•It’s nil instead of null.


INSTALLATION
▪Ruby is a cross platform programming language. It is installed differently on
different operating systems.

▪For UNIX like operating system, use your system's package manager.

▪For Windows operating system, use RubyInstaller.

▪For OS X system, use third party tools (rbenv and RVM).

▪We will install Ruby on Linux Ubuntu using package manager.

➢Debian GNU/Linux and Ubuntu use the apt package manager. Use the
following command:
sudo apt-get install ruby-full
(Continuation)
INSTALLATION
(Continuation)
INSTALLATION
➢To know your Ruby version installed in your system, use the command,

ruby -v
Simple HELLO WORLD program
▪Create a text file called hello_world.rb containing the following code:

puts 'Hello, world!'

▪Now run it at the shell prompt.

$ ruby hello_world.rb
Hello, world!

▪You can also run the short "Hello, world" program without creating a text file at
all. This is called a one-liner.

$ ruby -e "puts 'Hello, world'"


Hello, world

▪Option -e means evaluate (Ruby code).


(Continuation)

Simple HELLO WORLD program


▪You can run this code with irb, but the output will look slightly different.

▪puts will print out "Hello, world!", but irb will also print out the return value
of puts - which is nil.

$ irb >> puts "Hello, world!"


Hello, world!
=> nil
CLASSES AND OBJECTS
▪Ruby is a perfect Object Oriented Programming Language.

▪The features of the object-oriented programming language include :

➢Data Encapsulation

➢Data Abstraction

➢Polymorphism

➢Inheritance
(Continuation)
CLASSES AND OBJECTS
Defining a Class in Ruby
▪To implement object-oriented programming by using Ruby, you need to first learn
how to create objects and classes in Ruby.

▪A class in Ruby always starts with the keyword class followed by the name of the
class. The name should always be in initial capitals. The class Customercan be
displayed as :
class Customer
end
VARIABLES
▪Ruby provides four types of variables :
➢Local Variables: Local variables begin with a lowercase letter or _.

➢Instance Variables: Instance variables are preceded by the at sign (@)


followed by the variable name.

➢Class Variables: Class variables are preceded by the sign @@ and are
followed by the variable name.

➢Global Variables: global variables are always preceded by the dollar sign ($).
▪Example:
➢Using the class variable @@no_of_customers, you can determine the number
of objects that are being created. This enables in deriving the number of
customers.
class Customer
@@no_of_customers = 0
end
(Continuation)
CLASSES AND OBJECTS
Creating Objects in Ruby using new Method
▪Objects are instances of the class. You will now learn how to create objects of a
class in Ruby.

▪You can create objects in Ruby by using the method new of the class.

▪The method new is a unique type of method, which is predefined in the Ruby
library. The new method belongs to the class methods.

▪Here is the example to create two objects cust1 and cust2 of the class Customer −

cust1 = Customer. new


cust2 = Customer. new
(Continuation)
CLASSES AND OBJECTS
Custom Method to Create Ruby Objects
▪You can pass parameters to method new and those parameters can be used to initialize class
variables.
▪When you plan to declare the new method with parameters, you need to declare the
method initialize at the time of the class creation.
Eg:
class Customer
@@no_of_customers = 0
def initialize(id, name, addr)
@cust_id = id
@cust_name = name
@cust_addr = addr
end
end
▪Now, you can create objects as follows:
cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")
(Continuation)
CLASSES AND OBJECTS
Member Functions in Ruby Class
▪In Ruby, functions are called methods.

▪Each method in a class starts with the keyword def followed by the method name.

▪The method name always preferred in lowercase letters. You end a method in
Ruby by using the keyword end.

▪Here is the example to define a Ruby method :

class Sample
def function
statement 1
statement 2
end
end
OPERATORS
•Ruby Arithmetic Operators : + , - , * , / , % , **

•Ruby Comparison Operators : ==, !=, <, >, <=, >=, <=>, ===,.eql?, .equal?

•Ruby Assignment Operators : = and all short hand notation

•Ruby Bitwise Operators: & , | , ! , ~ , << , >>

•Ruby Logical Operators: and, or, not, &&,|| ,!

•Ruby Ternary Operator: ?:

•Ruby Range Operators: .. , ...

•Ruby defined? Operators : defined? variable


COMMENTS
•Comments are lines of annotation within Ruby code that are ignored at runtime.

•A single line comment starts with # character and they extend from # to the end
of the line .

•You can comment multiple lines using =begin and =end

Eg:-
=begin
This is a multiline comment and con spwan as many lines as you
like. But =begin and =end should come in the first line only.
=end
Ruby - if...else, case, unless
•If..else
Syntax
if conditional [then]
code...
[elsif conditional [then] •case statement
code...]... Syntax
[else case expression
code...] [when expression [, expression ...] [then]
end code ]...
[else
code ]
•unless statement end
Syntax
unless conditional [then]
code
[else
code ]
end
LOOPING
•Ruby while Statement
Syntax
while conditional [do]
code
end

•Ruby until Statement


Syntax
until conditional [do]
code
end
•Ruby for Statement
Syntax
for variable [, variable ...] in expression [do]
code
end
Continue..
Ruby break Statement
#!/usr/bin/ruby
for i in 0..5
if i > 2 then
break
end
puts "Value of local variable is #{i}"
End

Ruby next Statement


#!/usr/bin/ruby
for i in 0..5
if i < 2 then
next
end
puts "Value of local variable is
#{i}"
end
Continue..

Ruby redo Statement


#!/usr/bin/ruby
for i in 0..5
if i < 2 then
puts "Value of local variable is #{i}"
redo
end
end
METHODS
•Ruby methods are used to bundle one or more repeatable statements into a single
unit.

•Method names should begin with a lowercase letter.

•If a method begin by 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.
Continue..

Syntax

•def method_name
expr..
end

•def method_name (var1, var2)


expr..
end

•def method_name (var1 = value1, var2 = value2)


expr..
end
Continue..

Invocation statement

•method_name
•method_name 25,30

Return Values from Methods

•Return
•return 12
•return 1,2,3
CLASS METHOD
•When a method is defined outside of the class definition, the method is marked as
private by default.

•On the other hand, the methods defined in the class definition are marked as
public by default.

•Syntax
class Accounts
def reading_charge
end
def Accounts.return_date
end
end
BLOCKS
•A block consists of chunks of code.

•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.

•Invoke a block by using the yield statement.


Continue..

#!/usr/bin/ruby
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"}

•BEGIN and END Blocks


MODULES
•Modules are a way of grouping together methods, classes, and
constants.

•Modules give you two major benefits

•Modules provide a namespace and prevent name clashes.

•Modules implement the mixin facility.

•Syntax
module Identifier
statement1
statement2
...........
end
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.

•Ruby arrays can hold objects such as String, Integer, Fixnum,


Hash, Symbol, even other Array objects.

•Ruby arrays grow automatically while adding elements to them.


Continue..

Creating array

•names = Array.new
• names = Array.new(20)
• nums = Array.[](1, 2, 3, 4,5)
• nums = Array[1, 2, 3, 4,5]

Initializing array

•names = Array.new(4, "mac") #output: ["mac", "mac", "mac", "mac"]


•nums = Array.new(10) { |e| e = e * 2 } #output : [0, 2, 4, 6, 8, 10, 12,
14, 16, 18]
•digits = Array(0..9) #output :[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
HASH
•A Hash is a collection of key-value pairs like this:
"employee" = > "salary"

•It is similar to an Array, except that indexing is done via arbitrary keys of any
object type, not an integer index.

•The order in which you traverse a hash by either key or value may seem arbitrary
and will generally not be in the insertion order.

•If you attempt to access a hash with a key that does not exist, themethod will
return nil.
Continue..

Example:
H = Hash["a" => 100, "b" => 200]
puts "#{H['a']}"
puts "#{H['b']}"
DATE AND TIME
•The Time class represents dates and times in Ruby. It is a thin layer
over the system date and time functionality provided by the
operating system.

•Getting Current Date and Time


#!/usr/bin/ruby -w
time1 = Time.new
puts "Current Time : " + time1.inspect
# Time.now is a synonym:
time2 = Time.now
puts "Current Time : " + time2.inspect
RANGES
•Ranges as Sequences
•Ranges as Conditions
•Ranges as Intervals
FILE I/O
•Ruby provides a whole set of I/O-related methods
implemented in the Kernel module.

•All the I/O methods are derived from the class IO.

•The class IO provides all the basic methods, such as read,


write, gets, puts, readline, getc, and printf.
EXCEPTIONS
•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 provide 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.

You might also like