Friday, 10 October 2014

The Structure & Execution of Ruby Programs

1. Lexical Structure
     1) Ruby interpreter parses a program as a sequence of tokens
     2) Tokens include comments, literals, punctuation, identifiers & keywords
          1] Literals
              - values that appear directly in Ruby source code
              - include numbers, strings of text & regular expressions
              - e.g. 1        # An integer literal
                       1.0     # A floating point literal
          2] Identifiers
              - simply name
              - Ruby uses identifiers to name variables, methods, classes etc
              - consists of letters, numbers & underscore characters but may not begin with a number & may not include whitespace
              - Ruby is case sensitive language, Lowercase letters & uppercase letters are distinct
         3] Whitespace
             - Space, tabs & newlines
             - Semicolon can be used to terminate statements but only required if more than one statement on same line.

2. File Structure
    1) Shebang Comment 
        - tell the operating system how to execute it
        - If program contains this comment then it must appear on first line
    2) Coding Comment
        - If program contains this comment then it must appear appear after Shebang
    e.g
    #!/usr/bin/ruby -w            shebang comment
    # -*- coding: utf-8 -*-     coding comment
    require 'socket'                load networking library
   
    -----                               program code goes here

    _END_                           mark end of code
    ---                                   program data goes here

3. Program Encoding
- By default , the ruby interpreter assumes that Ruby source code is encoded in ASCII

4. Program Execution
- Ruby is a scripting language





































  

Thursday, 9 October 2014

Expressions in Ruby

1. Control structure like If returns value true or false
2. Loops & Method defination returns nil

Ruby Package Management with gem

1. Ruby Package management system is known as RubyGems & packages/modules distributed using RubyGems are called gems
2. Commands
    1) gem install
        - Installs most recent version of requested gem
    2) gem list
        - List installed gems
    3) gem environment
        - Display RubyGems configuration information
    4) gem update rails
        - Update a named gem
    5) gem update
        - Update all installed gems
    6) gem update --system
        - Update RubyGems itself
    7) gem uninstall rails
        - Remove an installed gem

String in Ruby

1. Strings are mutable.
2. freeze method is used to prevent any future modifications to object
3. String Interpolation - variables substituted into string. #{}

Range in Ruby

Range represents values(usually integers) between two end points
e.g.
  1..3      # All x where 1 <= x <= 3
  1...3     # All x where 1 <= x < 3

Regexp in Ruby

A Regexp (regular expression) object describes a textual pattern & has methods for determining whether a given string matches that pattern or not
e.g. /[Rr]uby/ # Matches 'Ruby' or 'ruby'

Variables in Ruby

1. Global variable - prefixed with $
2. Instance variable - prefixed with @
3. Class variable - prefixed with @@

Methods in Ruby

1. Method is defined with def keyword
2. Return value of method is the value of the last expression evaluated in its body
    e.g. def square(x)     # Define a method named square with one parameter x
              x*x                # Return x squared
         end                     # End of the method
3. Parentheses are usually optional
4. It can return more than one value.
5. Methods name can ends with =, ?, !
    e.g. Array & Hash classes define methods name empty? that return Boolean value - test whether the data structure has any elements
    - method without exclamation mark returns modified copy of the object where as method with explanation mark alters the object in place
      e.g. sort & sort!
6. Method outside class/module is global Function
7. Method defined on individual objects by prefixing the name of the method with the object on which it is defined is called as Singleton method
8. Class Method
    def Math.square(x)     # Define a class method of the Math module
         x*x
    end
9. Math module is part of core Ruby library & this code adds a new method to it

Operators in Ruby

No.
Symbol
 Name            
Use
Example
Overridable?
1.
+
Plus
- when used with integer operands then it is used for addition of two integers
- when used with string operands then it is used for concatination of two strings
1 + 2    
# => 3
                                                          'Ruby' + 'rocks!'
# => 'Ruby rocks!'


2.
*
Multiplication
- when used with integer operands then it is used for multiplication of two integers
- when used with one integer operand & one string operand then it repeats the string
1 * 2    
# => 2


'Ruby! ' * 3    
# => 'Ruby! Ruby! Ruby! '


3.
==
Equality
tests equality

1 + 2 == 3    
# => true

4.
**
Power of

2 ** 1024    
#  => 2 to the power 1024

5.
? :
Conditional

max = x > y ? x : y

6.
<< 

- integer classes Fixnum & Bignum uses this operator for bitwise left shift
- String, Array & Stream use this operator for an append operation


7.
[]

- Array class use this operator to access array elements by index
- Hash class use this operator to access hash values by key


8.
[]=

- this operator used to allow value on right hand side of an assignment will be passed as the final         argument to the method.
- allows to alter characters of a string or to insert,delete& replace substrings


9.
= = =
Case equality



10.
=
Assignment
- Ruby supports parallel assignment
 x, y = 1, 2           # Same as x = 1; y = 2

a, b = b, a        
# Swap the value of two variables

x,y,z = [1,2,3]  
# Array elements automatically assigned to variables
Nonoverridable
11.
+=
Increment

x += 1

12.
-=
Decrement

y -= 1

Hashes in Ruby

1. It is a fundamental data structure in Ruby
2. It is based on hashtable data structure & serve to map arbitrary key objects to value objects
3. e.g. h = {                       # A hash that maps number names to digits
                    :one => 1,     # The 'arrows' show mappings: key => value
                    :two => 2      # The colon indicates Symbol literals
                }
4. It uses square brackets to query & set
5. Hash class also defines each iterator
6. It can use any object as a key but symbol objects are the most commonly used as they are immutable

Wednesday, 8 October 2014

Blocks in Ruby

Code within curly braces or delimited with do/end which may associated with method invocation & serves as the body of loop are called as Blocks in Ruby

Iterators in Ruby

1. Iterators are nothing but special kinds of methods which behaves like loops.
2. e.g. times, upto, downto iterators of integer
    1) 3.times {print 'Ruby!' }      # Prints 'Ruby! Ruby! Ruby!'
    2) 1.upto(9) {|x| print x}         # Prints '123456789'
    3) 9.downto(1){|n| print n}     # Prints '987654321'
3. each, map, select & inject are also Array iterators
     1) a = [3, 2, 1]         # This is an array literal
         a[3] = a[2] - 1     # Use square brackets to query & set array elements
         a.each do |elt|      # each is an iterator. The block has a parameter elt
              print elt+1      # prints '4321'
         end                      # This block was delimited with do/end instead of {}
     2) a = [1, 2, 3, 4]                         # Start with an array
         b = a.map {|x| x*x}                # Square elements: b is [1, 4, 9, 16]
         c = a.select {|x| x%2==0|}     # Select even elements: c is [2, 4]
         a.inject do |sum,x|                  # Compute the sum of the elements => 10
              sum + x
         end
4. each is an iterator of Hash as well

Comments in Ruby

1. Ruby comment begins with # character & continue to the end of the line
    e.g. 1.class     # => Fixnum: the number 1 is a Fixnum
2. Ruby supports another style of multiline comment known as an Embedded document.
    - start on line that begins =begin & contu\inue until a line that begins =end
3. rdoc tool extracts documentation comments from Ruby source & formats them as HTML

Introduction of Ruby

  1. Ruby draws inspiration from Lisp, Smalltalk & Perl.
  2. It is purely object oriented language but also suitable for procedural & functional programming styles.
  3. It can be used to create domain-specific languages or DSLs.
  4. Yukihiro Matsumoto (known as Matz) is creator of Ruby.
  5. irb (shorts for 'interactive Ruby') is a ruby shell
  6. ri is documentation viewer                                                                                                             ri stands for Ruby Index/ Ruby Information/ Ruby Interactive                                                     e. g. ri Array  # provides documentation of Array Class    
     Features of Ruby
  1. Iterators & Blocks
  2. ability to associate a block of code with a method invocation
  3. Classes & Modules are 'open' & can be modified & extended at runtime