Page List & Sample Material (Repaired)
-
Upload
muhammad-haseeb-shahid -
Category
Documents
-
view
13 -
download
0
Transcript of Page List & Sample Material (Repaired)
This file contains 2 sections:
1: Chapter & Headings2: Sample Content
Chapter & Headings
Introduction To Ruby* What is Ruby * Origin of Ruby * Version History * Language Features* Supported Operating Systems* Installation Options* Using irb (as a REPL tool)* Running ruby tools (ruby -v, ri,rdoc)* Create a Hello World * Shebang (on Unix) * ftype on Windows
IDEs* Editing Ruby in a text editor* Benefits of IDEs* List of IDEs* Using Eclipse* Create Hello World in Eclipse
Language Fundamentals* Script Structure * Function * Blocks* Reserved Words* Syntax Rules* Naming Identifiers* Comments
Datatypes* What is a Datatype * List of Datatypes * Literals* Numbers* String* Boolean* Time* Nil* Constants * Creating * Predefined __FILE__, __LINE__, ARGV, DTA* Variables
* Local * Instance * Class * Global * Pseudo
String Closer Look* Single quotes * %q* Double quotes * %Q* Escape Sequences* Assignment (reference vs value)* Interpolation* Here documents* String methods
Collections* What are collection types * Array intro * Hash intro* Arrays* Creating Arrays* Adding values to Arrays* Ranges* Useful Array Methods* Hash* Creating Hash* Subscripting with Symbols* Useful Hash Methods
Operators* Arithmetic* Relational* Logical* Concatenation* Assignment * Shorthand * Multiple Assignment * Parrallel Assignment * Conditional Assignment
Branching Statements* What is branching* if
* unless* if-else* if-elsif-else* short-if* case
Loops* while* until* for* Loop modifiers * break * next * redo* Iterators * Introduction * do/end * { } * Numerical Iterators * String Iterators * Collection Iterators
What Is Ruby
Ruby is a server-side, object-oriented scripting-language.
Ruby development was started in 1993 by Yukihiro “Matz” Matsumoto.
Ruby was developed as an alternative language to Perl and Python and borrows from both languages.
Many operations support both the Perl & Python constructs. E.g. both || (Perl) and or (Python) are supported.
Ruby runs on Linux, Mac and Windows operating systems.
It is pre-installed on Macs and certain versions of Linux.
Like other languages, Ruby has undergone various revisions.
Version 1.9.0 was released in December 2007.
Version 2.0.0 was released in February of 2013.
Version 2.2.0 was released in December of 2015.
Language Features
Ruby is a fully object oriented language. Everything is an object instance including literals. Every object has a type. This type is the class the object
is based on. Every object has methods
Ruby is flexible and allows you to create the following types of code: Classes: These are structures that hold data and
methods Modules: These are groupings of methods. Scripts: Ruby also allows you to write executable script
outside of both classes and modules.
Ruby is dynamically typed.
Ruby is interpreted. Which means the code must be available at execution time.
Supported Operating Systems
Ruby is supported by all major operating systems i.e Linux, Mac OS X, Windows.
Ruby comes pre-installed on Mac OS X and many distributions of Linux.
Ruby is available on Windows too and is fully supported there.
Ruby runs slower on Windows, since the ‘require’ statement in Ruby scripts take a good chunk of time on Windows platform.
Ruby (v 1.9.2 ) has passed all the core tests on Windows.
Installation Options
In Mac OS X, Ruby can be installed with the following options:
RVM
Homebrew
Fink
MacPorts
In Linux systems, each variant has its own way to install Ruby.
Debian/Ubuntu systems use Synaptic or apt.
Red Hat Linux uses command line tool RPM
Ruby can be installed on Windows in following ways:
Downloading compiled binaries from Ruby site
RubyInstaller
Cygwin
Using IRB
Ruby comes in interactive mode too which can be put into use by using Interactive Ruby Shell( irb).
IRB acts as a read-eval-print loop tool for Ruby where actual Ruby code can be executed.
IRB can be used by typing irb in a UNIX-based shell prompt.
IRB output is slightly different than the actual Ruby output in the following way:
An assignment in IRB also prints out that assigned value while in actual Ruby code, the value is not printed just assigned.
Running Ruby Tools
There are several handy tools that can be used along with Ruby
ruby –v
RDoc
Ri
RDoc is a Ruby gems that automatically creates documentation from the comments and structure of your Ruby code.
Ri provides offline help for Ruby and acts as a command line manual for Ruby language.
ri Enumerator will open docs for Enumerator class.
Create a Hello World
In Unix systems create a hello_world.rb file and include a shebang line on top of the script. Shebang is ignored by interpreter as it is treated as a comment.
Shebang line cannot be preceded by blank lines or any leading spaces.
It is used by shell to determine which program to use to run the script
In Windows command prompt, use ftype command to point to the ruby.exe installation path.
Editing Ruby in Text Editor
Ruby code can be written in any text editor. Some of the popular text editors to write Ruby code are:
TextMate is a Mac OS X text editor.
Sublime Text is available on Linux, Mac OS X and Windows.
Vim is available on Linux systems.
Emacs is a popular Vim alternative.
Benefits of IDE’s
Code completion and code insight
Resource Management
Debugging tools
Less time to build project.
Easier Project Management
List of IDE’s
IDE is one of the most important part tools in a developer’s kit. The most popular IDE’s for Ruby are following:
IntelliJ’s RubyMine
Aptana
RedCar
NetBeans
Eclipse
Using Eclipse
Eclipse provides support for Ruby with Ruby Development Tools (RDT) plug-in.
Allows navigation of Ruby files within a Ruby project.
Hello World with Eclipse
Create a file with a .rb extension in eclipse after downloading RDT plugin.
Use the puts statement to print out “Hello World” in the console.
Script Structure
Blocks and functions are one of the many important parts of a Ruby script.
Keeping with Ruby’s object-oriented design, the functions are called methods in Ruby.
Defined with the def keyword
Return keyword can be used to explicitly return a value.
Value of the last line executed is returned if return not used.
Accepts default value for arguments as well as variable length arguments.
Any code surrounded by {…} are blocks in Ruby. But blocks are more powerful than just that.
They are also everything inside do…end part in Ruby code.
They are also used to construct Proc objects.
They can be passed to methods as arguments. One per method.
Yield keyword used inside methods to evaluate a block.
Reserved Words
Ruby has some reserved words which can’t be used as identifiers.
Some of the reserved words in Ruby v2.1.0 are :
BEGIN
END
case
self
yield
super
Naming Identifiers
Identifier’s name can be made up of alphanumeric characters and underscores but cannot start with a digit.
Identifier’s name length is only limited by a computer’s memory, otherwise no restrictions.
Identifiers which are method names can end with a question mark, equals sign or exclamation mark.
Reserved words cannot be used as identifiers.
Comments
Single line comments start with a # character to the end of the line.
To comment several lines of code, you can use the # symbol at the start of each line. But this will be inconvenient. A better approach is to use the Ruby multiline comment feature.
This is done by using the =begin and =end tags at the start of the lines you wish to comment.
Every statement between these tags is considered a comment.
What is Datatype
Datatypes are the types of “things” that are used to represent data in a programming language.
Literals are the values we assign to a variable.
Ruby supports various data types:
Boolean
Number
String
Array
Hash
Literals include:
Booleans and nil
Symbols
Regular expressions
Procs
Ranges
Arrays
Numbers
Numbers consist of two main data types. Integer and Floats.
Integers are number with no decimal place. They are objects in Ruby.
10/3 will yield 3 instead of 3.333 since both of the numbers are integers.
Since they are objects, they have methods defined onto them e.g. 3.times {block}
Floats are numbers with decimal places.
10.0/3 will yield 3.333 since one of the numbers is a float.
Strings
Since everything is an object in Ruby, strings are also objects belonging to the class String.
Simplest string literals are enclosed by single quotes.
String literals can also contain Ruby variables through expression substitution.
Strings can also be concatenated in Ruby through multiple ways. The plus operator (+) is one of the methods.
Every time a string literal is used for assignment, a new String object is formed.
A lot of methods are defined on String objects:
upcase
downcase
length
One can even open the String class at runtime and define their own methods for the String class.
Boolean
Booleans in ruby, just like any other programming language can just take one of these two values:
true
false
They are used to branch out our code according to conditionals.
Booleans in ruby are different from truthy and falsey values.
Time
Time class represents dates and times in Ruby. Storing dates and time in string literals is bad and not recommended at all.
There are minor differences between Time and DateTime in Ruby.
DateTime has minor understanding of time zones and no concept of daylight time savings.
DateTime has no concept of leap seconds.
Nil
Nil is an object in Ruby too.
nil.class actually returns NilClass.
5.nil? and nil.nil? are valid Ruby statements.
Object_id of nil equals 4 as nil is a singleton instance of NilClass.
Constants
Constants start with capital letters. “Foo” is a constant while “foo” isn’t.
Ruby allows you to redefine and modify the value of constants but gives a warning during redefining.
Constants can be frozen by using method “freeze” on constants which will not allow modification of constants.
Ruby has some predefined constants too:
_File_
_Line_
ARGV
DTA
Variables
Local variables name begins with a lowercase letter or underscore.
Accessible from within the blocks of its initialization.
Scope ends when the function returns.
Instance variables name begin with @ symbol.
They belong to an instance. Each instance has its own copy.
Uninitialized instance variables are nil by default.
They are not passed along the inheritance chain.
Class variables belong to the class unlike instance variables
They are denoted by @@ syntax.
Class variables shared by all descendents of the class.
Act like global variable visible just in the inheritance tree.
Global variables start with a $ symbol. They can be accessed anywhere in the program during runtime.
Pseudo variables are predefined and we cannot assign values to them. Some of these are :
self
nil
true
Single Quotes
Single quoted strings cannot be interpolated.
Single quoted strings can’t be used for expression substitution.
Single quoted strings are not subject to escape sequences except for escaping single quotes themselves.
%q is shorthand syntax to generate single quoted string literals.
Double Quotes
Double quoted strings can be interpolated. Expression substitution can be performed with double
quoted string literals. They are subject to escaping sequences. %Q is shorthand syntax for double quoted strings.
Escaping sequences
Some of the escape sequences used inside double quoted string literals are:
\” – double quote \\ - single backlash \b – backspace \n – newline \s – space \t – tab
Assignment (Reference vs value)
String assignment (a = “hello”) always creates new object_ids.
String assignment (b = a) always stores reference of string variable.
Assigning new value to either “a”or “b” won’t affect each other’s values.
Usage of methods like gsub! on one string will affect the value of other one since it will change the value present at the reference.
Interpolation
Interpolation allows Ruby code to appear within a string.
Expression can be any valid Ruby code. Interpolation requires double-quoted string literals. Automatically calls to_s on the result.
Here document
Here document is constructed by << symbol followed by the identifier marking end of the document.
End mark is called terminator. Here documents are interpolated unless single quotes
are used around the delimiter. Multiple here documents can be used together too.
String methods
Strings have a lot of methods defined onto them. Some of the methods are :
capitalize returns the string with first character in upper case.
upcase returns the string with lowercase letters replaced with their uppercase counterparts.
downcase returns the string with uppercase letters replaced with their lowercase counterparts.
split divides string into substrings based on delimiter and returns an array.
hash sums up the characters in a string. sum returns a n-bit checksum of the characters in
string.
What are collection types
Collections types are the data types which can hold more than one item.
The most used collection types in Ruby are: Arrays Hashes
Arrays hold items against an index with random access. Hashes hold items in key/value pairs.
Arrays
Arrays can hold different data types in Ruby. A single array can consist of strings, integers and even booleans.
Arrays are indexed by a non-negative integer when accessed from start.
Negative integer index accesses the array from the last.
Creating Arrays
Arrays can be created in two ways: array = [] Array.new %w String splitting
In all of the cases, a new array object is constructed in memory possessing an object_id.
%w delimiter is used to convert single or double quoted string literals into arrays.
Splitting a string with a delimiter converts strings into arrays.
Adding values to arrays
There is more than one way to add a value in an array object.
<< syntax push method unshift insert
<< and push adds elements to the end of array. Unshift method adds elements to the start of the array Insert method can be used to add element at any index.
Ranges
Arrays can be accessed through range of indexes too e.g a[1..3]
Range has a start point and an end point separated by double periods or triple periods.
The end position is counted with double periods but omitted with tripe periods.
Useful Array Methods
Array objects have a lot of handful method defined unto them.
each iterates over a collection with an iterator variable holding enumerable value one by one.
each_with_index iterates over a collection with two iterator variables representing the enumerable and the index of the enumerable respectively.
map is same as each except it returns the modified enumerable unlike each which returns the original object.
collect is same as map. More like an alias fofor map.
sample chooses a random element(s) from an array.
permutation yields all permutations for n element of an array.
flatten extracts all the elements of an array which itself are an array into a new array.
Hash
Hash is a way to store a collection of data in key/value pairs.
A key can only appear once in a hash. The keys can be strings, symbols or even integers.
Mostly, strings and symbols are preferred.
Creating Hash
Hashes can be constructed in two ways: Explicitly declaring the hash with curly braces {} Hash.new
The value of hash when not initialized is {}. The default value of a hash can be specified when by
passing a parameter to Hash.new(“greeting”). This sets the default value to “greeting”.
Subscripting with symbols
Ruby symbol is an internal representation of the name. Ruby symbols have the same object_id throughout the
application unlike strings which represent different objects with same literals.
They are only initialized once. They don’t store values or objects. After Ruby 2.2.0, symbols can now be garbage collected
too.
Symbol.all_symbols results in all the symbols predefined in Ruby other than the ones we create.
Useful Hash Methods
Hashes are equipped with some very handy methods: merge combines one hash with other. each iterates over a hash providing a key and
value against it as iterator variables. has_keys? checks if a hash contains key(s). map
Arithmetic Operators
Ruby has all the basic arithmetic operators + Adds the values on both sides of it. - Substracts the value on the right of the operator
from the one of the left. * Multiplies the operands. / Divides the number on left by the number on
right of it. % - Modulus operator. Gives the remainder of a
division operation. ** - Exponent operator. 2**3 i.e 8
Relational Operators
Relational operators are constructs that define relationship between two entities.
== checks the equality of left and right side variables.
!== checks if the left and right side are not equal. > checks if the left side is greater than the right
side. < checks if the left side is smaller than the right
side. >= checks if the left side is greater than or equal
to right side. <= checks if the left side is smaller than or equal
to the right side. <=> is called the spaceship operator. It returns 0,
-1, 1 after comparing the left value to the right value. If equal, it returns 0. If left is greater then right, it returns 1. If left smaller then right, it returns -1. It returns nil otherwise.
=== checks for equality of value and type of the operands.
Logical Operators
Logical operators are more commonly called Boolean operators.
and, or, not are logical operators and each of them come in two versions
and, && or and || not and !
The latter versions of each of them have higher precedence than their former part.
Assignment Operators
Operators used to assign new value to a variable. = (a = 5 assigns a value to a variable) += (a+=3 equals a = a+3) -= (a-= 3 equals a = a-3) *= (a*=3 equals a = a*3) /= (a/=3 equals a = a/3) %= (a%=3 equals a = a%3) **= (a**=3 equals a = a**3) ||= (a||=b will assign a to b only if a is undefined
or nil) Ruby lets you assign multiple variables at once.
Supports multiple assignment e.g a,b = 3,4. Parallel assignment works by comparing the left hand
side, also called the receiving side, to the right-hand side.
What is Branching
Conditional branching takes the result of an expression and further executes code based on whether the result of expression is true or false.
There are many control structures that provide such branching
if else-if unless while case
If expression
If expressions execute code based on the Boolean value provided to if condition.
If expression is terminated by the end statement. If expression is one of the most basic element and
control structure often used for branching inside a script.
If expression can be written in one line if followed by a then keyword.
If expression is evaluated on basis of a true-or-false values.
In Ruby’s context, true and false is a boolean, but there are some other truthy and falsey values that can be used to evaluate an if expression.
Only nil and false will evaluate to false in an if expression in Ruby.
If-else statement
The else case of the if-else statement executes when if clause evaluates to false.
So the else case will only be considered when if case evaluates to false.
If-elsif-else expression
The elsif and else blocks give you further control over your code since it accommodates further tests.
There is no limit on the number of elsif blocks but the if and else block can only be one.
Short-if expression
Short-if statement is a space-saving short way of evaluating an expression and returning a value.
The syntax is : (condition)? (expression if true) : (expression
if false) Also referred to as ternary operator.
Shortened if statements can also be written as: puts “hello” if a == 0
Case expression
Case is an alternative to the aforementioned if-elsif-else expression.
You give an expression to a case keyword and evaluate the choices in the when keyword.
The statement when can be supplied with more than one value.
When can also be evaluated against string computation and regular expressions.
The else keyword can be used as a default value provider for the case expression in the end.
While loop
It starts with the while keyword and ends with end keyword.
The code block in between will keep on executing as long as the expression provided to while statement evaluates to true.
The while loop can shortened too. <code> while <expression>
Until loop
Until statement has the exact same syntax as the aforementioned while loop.
Until and while loops are same in functionality except that until loop runs as long as the expression evaluates to false.
For loop
For loop is provided with an expression which can be iterated over. The expression can be a string, range or an array.
for is just syntax sugar for each method, the only difference being the scope of the iterator variable after the block ends.
It will throw an exception if the expression provided evaluates to nil.
Loop modifiers
Loop modifiers are constructs that can alter the normal flow of a loop.
Some of the loop modifiers are: break redo next
break alters the normal flow of a loop by breaking out of the entire loop on some condition.
redo repeates the current iteration on some condition
next immediately continues to the next iteration in the loop on some condition.
Iterators
Iterators are methods supported by collection objects.
They return all the elements of the collection, one after the other.
Most common type of iterators are : Numerical String Collection
Numerical iterators iterate on a number and the code block gets executed that number times.
times upto
String iterators iterate on a string literal. each_char
Collection iterators iterate on collection objects. collect map each