Ruby is the interpreted scripting language for quick and easy object-oriented programming. It has many features to process text files and to do system management tasks (as in Perl). It is simple, straight-forward
The language was created by Yukihiro “Matz” Matsumoto, who started working on Ruby on February 24, 1993, and released it to the public in 1995.
Installation
• The Windows installation of Ruby is a breeze. First, you need to download the Ruby installer. There might be a couple of versions to choose from; this tutorial is using version 1.8.4, so make sure what you download is at least as recent as that. (I would just get the latest version available.) Then simply run the installation program. It will ask you where you want to install Ruby. Unless you have a good reason for it, I would just install it in the default location.
Ruby Features
-> Ruby has simple syntax
-> Ruby has exception handling features, like Java or Python, to make it easy to handle errors.
-> Ruby is a complete, full, pure object oriented language: OOL. This means all data in Ruby is an object, in the sense of Smalltalk: no exceptions. Example: In Ruby, the number 1 is an instance of class Fixnum.
-> Operator overloading
-> Automatic garbage collecting
-> Ruby can load extension libraries dynamically if an OS allows
-> Ruby is highly portable: it is developed mostly on Linux, but works on many types of UNIX, DOS, Windows 95/98/Me/NT/2000/XP, MacOS, BeOS, OS/2, etc.
-> Ruby features blocks in its syntax (code surrounded by ‘{’ … ‘}’ or ‘do’ … ‘end’)
-> Ruby’s OO is carefully designed to be both complete and open for improvements. Example: Ruby has the ability to add methods to a class, or even to an instance during runtime. So, if needed, an instance of one class *can* behave differently from other instances of the same class
Interactive Ruby (irb)
Interactive ruby is a shell for programming in Ruby. Interactive ruby IRB is run from the command line and allows the programmer to experiment with code in real time. It allows you to enter Ruby commands at the prompt and have the interpreter respond immediately. Open by clicking irb in command prompt and type
3/2 => 1, 3.0/2.0 => 1.5, 3**2 => 9, 5%2 => 1, 5.0 % 2 => 1.1
String In Ruby
-> String is set of characters
Examples
“hello”,”anand”
-> Run these in irb -
“hello “+”world”=Hello world
“hi ”*3=hi hi hi
-> Ruby provide sfollowing functions for strings
reverse -> “anand”.reverse
Upcase -> “anand”.uppercase
Downcase -> “anand”.downcase
Swapcase -> “anand”.swapcase
Length ->”anand”.lenght
Next -> “anand”.next
Class In Ruby
Class: Ruby separates everything into classes. Like integers, floats and strings.
Object: That’s just any piece of data. Like the number 3 or the string ‘hello’.
Method: These are the things that you can do with an object. For example, you can add integers together, so + is a method.
Example - Integer, Float, and String are classes
and +, -, /, *, %, **, capitalize, reverse,length, upcase are methods
Run this in irb-
12.is_a?(Integer)
Variables and Constant in Ruby
Variables A variable is a name that Ruby associates with a particular object.
Ruby support four levels of variable scope
Ruby needs no variable declarations. It uses simple naming conventions to denote the scope of variables.
Examples: ‘var’ => local variable,
‘@var’ => instance variable,
‘$var’ => global variable.
‘@@var’ => class variable
Constants are start with capital letter
Example: Var= ‘Anand’
First Program (Hello World) in Ruby
Open word pad and type this
Puts “Hello World”
Save the file by “hello.rb”
Open irb
Run the command
ruby hello.rb
It will produce
Hello World
Input from user
We use the gets method to get the user input (as a string).
Puts “enter number”
Num = gets
Puts “u entered”+num
O/P
“anand\n”
Num=gets.chomp
It will remove \n from string
Conditions and Loops In Ruby
Example 1>
4.times do
Puts “anand ”
End
Example 2>
Count=0
While count<10
Puts count
Count+=1
end
Conditions
if statements allow you to take different actions depending on which conditions are met.
If city == “Bangalore”
Puts “yes it is Bangalore”
Elsif city == “delhi”
Puts “no it is not Bangalore”
end
Arrays In Ruby
arrays You are already familiar with a couple of Ruby classes (Integer and String). The class Array is used to represent a collection of items.
Open IRB and run these commands
>> numbers = [ "zero", "one", "two", "three", "four" ]
=> ["zero", "one", "two", "three", "four"]
>> numbers.class
Þ Array
>> number[0]
=> “zero”
>>addresses = [ [ 284, "Silver Sprint Rd" ], [ 344, "Ontario Dr" ] ]
Þ [[284, "Silver Sprint Rd"], [344, "Ontario Dr"]]
>>addresses [0][0]
=>284
names = [ "Melissa", "Daniel", "Jeff" ]
Þ ["Melissa", "Daniel", "Jeff"]
>> names + [ "Joel" ]
Þ ["Melissa", "Daniel", "Jeff", "Joel"]
>> names * 2
=> ["Melissa", "Daniel", "Jeff", "Melissa", "Daniel", "Jeff"]
Iterator In Ruby
Iterator is a method that lets you access items one at a time.
Run In IRB
>>friends = ["Melissa", "Jeff", "Ashley", "Rob"]
friends.each do |friend|
puts “I have a friend called ” + friend
end
Hash In Ruby
Hashes are a generalization of arrays.
Instead of only permitting integer indices, as in array[3], hashes allow any object to be used as an “index“. So, you can write hash["name"]
friend = { “first name” => “Jeffrey”, “last name” => “Biggs”, “address” => “34 Airport Rd”, “city” => “Toronto”, “province” => “Ontario”}
Hashes have a Hash#each method, similar to Array#each. This method, however, supplies both they key and the value.
friend.each do |key, value|
puts key + ” => ” + value
End
Function and class declaration
class Address
attr_accessor :street
def initialize
@street = “”
End
def street=(street)
@street = street
end
End
Attr_reader
Attr_writer
Attr_accessor
A function is a method that is not associated with any particular object.
You have already seen one function: “puts“. Notice the syntax:
puts “Hello” # instead of: object.puts “Hello”
Exception Handling in Ruby
Rescue the exception with a begin/rescue block. The code you put into the rescue clause should handle the exception and allow the program to continue executing.
This code demonstrates the rescue clause:
def raise_and_rescue
begin
puts ‘I am before the raise.‘
raise ‘An error has occurred.’
puts ‘I am after the raise.’
rescue
puts ‘I am rescued!’
end
puts ‘I am after the begin block.’
end
o/p
raise_and_rescue
#I am before the raise.
# I am rescued!
# I am after the begin block.
The exception doesn’t stop the program from running to completion, but the code that was interrupted by the exception never gets run. Once the exception is handled, execution continues immediately after the begin block that spawned it.
Ruby’s Flexibility
Ruby is seen as a flexible language, since it allows its users to freely alter its parts. Essential parts of Ruby can be removed or redefined, at will. Existing parts can be added upon. Ruby tries not to restrict the coder.
class Numeric
def plus(x)
self.+(x)
end
end
y = 5.plus 6 # y is now equal to 11
Good tutorial man..