Ruby PDF
Ruby PDF
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.
Each and every code has their properties and actions. Here properties refer to
variables and actions refer to methods.
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
Rails
management platform
Now, here’s a single line of Ruby code that does the same thing:
Useful Features
This code:
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.
•All member variables are private. From the outside, you access everything via
methods.
•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};).
▪For UNIX like operating system, use your system's 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:
$ 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.
▪puts will print out "Hello, world!", but irb will also print out the return value
of puts - which is nil.
➢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 _.
➢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 −
▪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.
class Sample
def function
statement 1
statement 2
end
end
OPERATORS
•Ruby Arithmetic Operators : + , - , * , / , % , **
•Ruby Comparison Operators : ==, !=, <, >, <=, >=, <=>, ===,.eql?, .equal?
•A single line comment starts with # character and they extend from # to the end
of the line .
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
•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
Invocation statement
•method_name
•method_name 25,30
•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.
#!/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"}
•Syntax
module Identifier
statement1
statement2
...........
end
ARRAYS
•Ruby arrays are ordered, integer-indexed collections of any object.
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
•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.
•All the I/O methods are derived from the class IO.
•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.
•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.