INTRODUCTION TO RUBY

Ruby is a dynamic, reflective and general purpose OOP. Ruby supportsmultiple programming paradigms, including functional, object oriented,imperative and reflection.
IN THIS CHAPTER :
Introduction
Ruby has many strong features of various languages. It is a strong object oriented programming language. Ruby also has the scripting feature similar to Python and Perl.
History
During the mid-1990s, Ruby originated in Japan and was initially developed and designed by Yukihiro "Matz" Matsumoto. In 1994 David Heinemeier Hansson designed Rails frame work under MIT license system, and Ruby on Rails. The programming style of Ruby is similar to perl, python etc.
Ruby is different from other object oriented languages :
Number and String :
Numbers :
Ruby has some wonderful features working with numbers. Ruby supports integers and floating-point numbers. Integers can be of any length (up to a maximum determined by the amount of free memory on our system). Integers within a certain range ( normally -2e30 to 2e30 1 or -2e62 to 2e62 -1) are held internally in binary form and are objects of class Fixnum . Integers outside this range are stored in objects of class Bignum. This process is transparent and Ruby automatically manages the conversion back and forth.
Example :
num = 81
6.times do
puts "#{num.class}: #{num}"
num *= num
end
Result :
Fixnum: 81
Fixnum: 6561
Fixnum: 43046721
Bignum: 1853020188851841
Bignum: 3433683820292512484657849089281
Bignum: 11790184577738583171520872861412518665678211592275841109096961
In Ruby we can write integers using an optional leading sign, an optional base indicator ( 0 for octal, 0d for decimal[the default], 0x for hex and 0b for binary) followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string.
Example :
123456 => 123456 # Fixnum
0d123456 => 123456 # Fixnum
123_456 => 123456 # Fixnum underscore ignored
-543 => 543 # Fixnum negative number
0xaabb => 43707 # Fixnum hexadecimal
0377 => 255 # Fixnum octal
0b10_1010 => 42 # Fixnum binary (negated)
123_456_789_123_456_789 => 123456789123456789 # Bignum
Control characters can be generated using ?\C-xand ?\c-x (the control version of x isx & 0x9f). Metacharacters (x | 0x80) can be generated using ?\M-x.The combination of meta and control is generated using and ?\M-\C-x. We can get the integer value of a backslash character using the sequence ?\\.
?a => 97 # ASCII character
?\n => 10 # code for a newline (0x0a)
?\C-a=> 1 # control a = ?A & 0x9f = 0x01
?\M-a=> 225 # meta sets bit 7
?\M-\C-a=> 129 # meta and control a
?\C-?=> 127 # delete character
String :
Ruby strings are simply sequences of 8-bit bytes. They normally hold printable characters, but that is not a requirement; a string can also hold binary data. Strings are objects of class String. In Ruby we can write any string within single quotes or double quotes (like "test" or "test") . But there is a small difference between single quotes and double quotes. A double-quoted string allowsbr> character escapes by a leading backslash, and the evaluation of embedded expressions using #{}. A single-quoted string does not do this interpreting.
Example :
puts "a\nb\nc"
a
b
c
In Ruby,s there are several built in method that helps to format a string. There are follow :-
Alignment String:
ljust, rjust, and center are used to alignment a string.
Example :
s = "test "
s1 = s.ljust(13)
s2 = s.center(13)
s3 = s.rjust(13)
puts s1
puts s2
puts s3
Result :
test
test
test
Change case of String:
The downcase method will convert a string to lowercase. Same way upcase will convert it to uppercase.
Example:
s1 = "Test Code"
s2 = S1.downcase # test code
s3 = S1.upcase # TEST CODE
puts s2
puts s3
Result: test code,TEST CODE
String Concat:
a = "hello"
a.concat("world")
puts a
Result:
Hello world
Find Out the location of a string:
The index method will return the starting location of the specified substring, character.
s = "Circar Consulting"
position1 = s.index(?n)
position2 = s.index("car")
puts position1
puts position2
Result:
9
3
Length of a string :
The length is used to find the length of a string
Example:
str1 = "Circar"
x = str1.length
puts x
Result: 6
The include? method simply states whether the specified substring or character occurs within the string
Example:
s1 = "mathematics"
f1 = s1.include? ?e
puts f1
Result:
true
Chop Method:
The chop method removes the last character of the string (typically, a trailing newline character).
Example:
"string\r\n".chop #=> "string"
Chomp Method:
The chomp method is same to chop method but it does not return new line.
Split Method:
It is used to break a string into different string.
Example:
Str = "test,top, code"
puts str.split(".")
Result:
test
top
code
Whitespace Removing from a String:
The strip method will remove whitespace from the beginning and end of a string. Its counterpart strip.
Example:
s1 = "\n \nabc \t\n"
s2 = s1.strip
puts s2
Result:
abc
Convert the Number:
to_f and to_i are use to convert to floating point numbers and integers, respectively. Each will ignore extraneous characters at the end of the string, and each will return a zero if no number is found.
Example:
num1 = "23".to_i
Result: 23/
num2 = "2.25".to_f
Result: 2.25
String Reverse:
In Ruby, a string can be reversed very simply with the reverse method (or its in-place counterpart reverse!).
Example:
s1 = "Test"
s2 = s1.reverse
s1.reverse!
puts s2
puts s1
Results:
Test
Test
Remove Duplicate Character:
Duplicate characters can be removed using the squeeze method.
Example:
s1 = "rorguuru"
s2 = s1.squeeze
puts s2
Result:
rorguru
Delete String:
In Ruby, the delete method will remove characters from a string if they appear in the list of characters passed as a parameter.
Example:
s1 = "Be careful"
s2 = s1.delete("e")
puts s2
Result:
B carful
Count Method:
The count method will count the number of occurrences of any set of specified
characters.Example:
s1 = "rorguru"
a = s1.count("r")
puts a
Result:
3
Variable and Constant:
In Ruby, we can store data in variables which are named placeholders that can store numbers , strings and other data.Using the variables name we reference the data stored in a variable.
Example:
price = 50
puts price
Result:
50
There are five types of variables which are as follows :
1) Constants 2) Locals 3) Global  4) Instance and 5) Class variables
1. Constant Variable :
In Ruby, constant variable is a constant and it begins with an uppercase letter and it is defined within a class or module that may be accessed unadorned anywhere within the class or module and it should not be defined inside a method.
Example : Test, Value etc.
2. Local Variable :
In Ruby local variables can only be accessed from any part of the program. a local variable must begin with a lowercase letter or the ( _) underscore sign.
Example : var, _var, test_var .
3. Global Variable :
Global variables start with a dollar sign (``$'') followed by name characters and it can accessible globally to the program.
Example : $hi = "How are you"
puts $hi
4. Instance Variable :
Instance variables are associated to objects. Instance variables begin with the @ sign, an uninitialized instance also gives same as global variable.
Example : @hi = "How are you"
puts $hi
Result : How are you
5. Class Variable
Class variables belong to a class. Class variables are declared by prefixing the variable name with two @ characters (@@). Class variables must be initialized at creation time.
Example :
@@hi = "How are you"
puts @@hi
Result :@hi = "How are you"
Constant:
Ruby constants are values which once assigned a value should not be changed. Constants defined within a class or module may be accessed unadorned anywhere within the class or module. Outside the class or module, they may be accessed using the scope operator, ``::
Example:
OUTER_TEST = 20
class Test
def getTest
TEST
end
TEST = OUTER_TSET+ 1
end
Test.new.getTest =>21
Test::TEST =>21
::OUTER_TEST =>20
Operators:
In Ruby an operator which dictates the operation to be performed and the operands are placed either side of the operator.
There are several types of operators in Ruby which are listed below.
1. Assignment Operators: There are two types of operators a) Basic Assignment Operators b) Parallel Assignment Operators.
a) Basic Assignment Operators:
Basic assignment operator (=) which allows us to assign the result of an expression. The most common of this types of operators are shown below.
| OPERATORS | EQUIVALENT |
| a+=b | a= a+b |
| a-=b | a=a-b |
| a/=b | a=a/b |
| a*=b | a=a*b |
| a%=b | a=a%b |
| a**=b | a=a**b |
b) Parallel Assignment
In Ruby parallel assignment of variables to be initialized with a single line of Ruby code.
Example : a, b, c = 10, 20, 30.
Parallel assignment is also useful for swapping the values in two variables:
Example:
a, b = b, c
2. Arithmetic Operators:
| Operator | Description | ||
| + | addition | Adds values | |
| - | subtraction | Subtracts values | |
| * | multiplication | Multiplies values | |
| / | division | Divides left hand operand by right hand operand |
|
| % | modulus | Returns reminder | |
| ** | exponent | Performs exponential (power) calculation on operators |
3. Comparison Operators:
Comparison operators are used to compare two values. Ruby has a number of such operators:
Example :
==,or, .eql?,!=,<,>,<=,>=,<=>
4. Bitwise Operators:
| - | Bitwise NOT | |
| | | Bitwise OR | |
| & | Bitwise AND | |
| ^ | Bitwise Exclusive OR | |
| << | Bitwise Shift Left | |
| >> | Bitwise Shift Right |
Array and Hash :
Array
In Ruby, array are used to store a collection of data like other language. Arrays act as groups of variables and we can access each variable in an array with an index number.
Example:
array = ["welcome","to","rorguru"]
puts array[0]
puts array[1]
puts array.length
array2 = Array.new
puts array2.length
array2[0] = "Test"
array2[1] = "Code"
puts array2[0] + " " + array2[1]
puts array2.length
Result welcome
to
3
0
Test Code
2
Hash
In Ruby a "hash" sometimes called an associative array or a dictionary, is much like an array in that it holds a collection of data but we can index it using text strings as well as numbers.
Example :
sport = { "cricket" => "bat", "tennis" =>"racket"}
puts array[0]
puts sport["cricket"]
puts sport
puts sport.length
receipts = {"sachin" => 15000, "federar" => 15}
puts receipts ["sachin"]
puts receipts ["federar"]
Result :
bat
tennisracketcricketbat
2
15000
15
