rubyonrails(1,2) imp

Upload: krishna-sakinala

Post on 03-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 Rubyonrails(1,2) Imp

    1/56

    11stst DayDay

  • 7/28/2019 Rubyonrails(1,2) Imp

    2/56

    RUBYRUBY

  • 7/28/2019 Rubyonrails(1,2) Imp

    3/56

    Introduction to RubyIntroduction to Ruby

    Ruby is a pure object-oriented programmingRuby is a pure object-oriented programming

    language .language .

    A dynamic, open source programmingA dynamic, open source programming

    language with a focus on simplicity andlanguage with a focus on simplicity and

    productivity. It has an elegant syntax that isproductivity. It has an elegant syntax that isnatural to read and easy to write.natural to read and easy to write.

    Ruby was created by Yukihiro MatsumotoRuby was created by Yukihiro Matsumoto ..

  • 7/28/2019 Rubyonrails(1,2) Imp

    4/56

    Ruby FeaturesRuby Features

    interpretedinterpreted

    Object-orientedObject-oriented

    portableportable untypeduntyped

    Automatic memory-management(garbageAutomatic memory-management(garbage

    collection)collection) Easy and clear syntaxEasy and clear syntax

  • 7/28/2019 Rubyonrails(1,2) Imp

    5/56

    Other Features of RubyOther Features of Ruby

    Ruby is free, also for commercial applications.Ruby is free, also for commercial applications. many existing libraries make programming easy .many existing libraries make programming easy . Ruby is permanently developed, without loosingRuby is permanently developed, without loosing

    backward-compatibility .backward-compatibility . There are interfaces to Python, Perl and Java.There are interfaces to Python, Perl and Java.

    Thus existing programs can be reused.Thus existing programs can be reused. Many important data-structures are available (suchMany important data-structures are available (such

    as dynamic arrays (lists), strings, bignum,as dynamic arrays (lists), strings, bignum,

    complex, ....) .complex, ....) .

  • 7/28/2019 Rubyonrails(1,2) Imp

    6/56

    Ruby names:Ruby names:

    The first character of a name helps Ruby to distinguish itsThe first character of a name helps Ruby to distinguish its

    intended useintended use instance variable name starts with a @ signinstance variable name starts with a @ sign class variable name starts with a @@ signclass variable name starts with a @@ sign global variable name starts with a $ signglobal variable name starts with a $ sign constant name starts with an uppercase letterconstant name starts with an uppercase letter

    Method names should begin with a lowercase letterMethod names should begin with a lowercase letter ? and ! are the only weird characters allowed as method name suff? and ! are the only weird characters allowed as method name suff

    ixesixes ! or bang labels a method as dangerous-specifically! or bang labels a method as dangerous-specifically use underscores to separate words in a multiword method oruse underscores to separate words in a multiword method or

    variable namevariable name Class names, module names and constants use capitalizationClass names, module names and constants use capitalization

  • 7/28/2019 Rubyonrails(1,2) Imp

    7/56

    Ruby Features:Ruby Features:

    # Ruby is dynamic# Ruby is dynamic

    x = 7x = 7 # integer# integer x = "house"x = "house" # string# string x = 7.5x = 7.5 # real# real # In Ruby, everything you manipulate is an object# In Ruby, everything you manipulate is an object 'I love Ruby'.length'I love Ruby'.length

    The basic types in Ruby areThe basic types in Ruby are NumericNumeric (subtypes include(subtypes include FixnumFixnum,, IntegerInteger, and, andFloatFloat),), StringString,,ArrayArray,, HashHash,, ObjectObject,, SymbolSymbol,, RangeRange, and, and RegExRegEx. Ruby. Rubydoesn't require you to use primitives (data types) when manipulating data of thesedoesn't require you to use primitives (data types) when manipulating data of thesetypes-if it looks like an integer, it's probably an integer; if it looks like a string, it'stypes-if it looks like an integer, it's probably an integer; if it looks like a string, it'sprobably a string.probably a string. classclass returns the class of an object, for example:returns the class of an object, for example:

    s = 'hello's = 'hello' s.s.classclass # String# String

    In Ruby, everything you manipulate is an object, and the results of thoseIn Ruby, everything you manipulate is an object, and the results of thosemanipulations are themselves objects. There are no primitives or data-types.manipulations are themselves objects. There are no primitives or data-types.

  • 7/28/2019 Rubyonrails(1,2) Imp

    8/56

    StringsStrings String literals are sequences of characters between single or doubleString literals are sequences of characters between single or double

    quotation marks.quotation marks. puts "Hello World"puts "Hello World" # Can use " or ' for Strings, but ' is more efficient# Can use " or ' for Strings, but ' is more efficient puts 'Hello World'puts 'Hello World' # String concatenation# String concatenation puts 'I like' + ' Ruby'puts 'I like' + ' Ruby' "hello".index('lo') #=> 3"hello".index('lo') #=> 3

    "hEllO".upcase #=> "HELLO""hEllO".upcase #=> "HELLO" # New here, displays the string three times# New here, displays the string three times puts 'Hello' * 3puts 'Hello' * 3 mystring = suresh,firoz,naresh,rameshmystring = suresh,firoz,naresh,ramesh myarray = mystring.split(/,/)myarray = mystring.split(/,/)

    str =mystring.gsub(/firoz/,"Shyam")str =mystring.gsub(/firoz/,"Shyam") puts strputs str In Ruby, strings are mutable. They can expand as needed, without usingIn Ruby, strings are mutable. They can expand as needed, without using

    much time and memory. Ruby stores a string as a sequence of bytes.much time and memory. Ruby stores a string as a sequence of bytes.

  • 7/28/2019 Rubyonrails(1,2) Imp

    9/56

    Control StructuresControl Structures1)1)ififconditioncondition

    instruction1instruction1

    instruction2instruction2elseelse

    instruction3instruction3

    instruction4instruction4

    endend

    2) ifcondition1instruction1 ...

    instructionmelsifcondition2instructionm+1 .....instructionk

    elseinstructionk+1

    instructionlend

    3)Unless syntax is:

    unless condition

    instruction1else

    instruction2end

    3) Syntax for case statement:

    case variablewhen condition1

    intruction1

    when condition2instruction2 .......

    when conditionkinstructionk

    elseinstructionk+1

    end

  • 7/28/2019 Rubyonrails(1,2) Imp

    10/56

    LoopsLoops

    The While loopCode example:i = 0while i

  • 7/28/2019 Rubyonrails(1,2) Imp

    11/56

    Regular ExpressionsRegular Expressions

    Regular expressions are put between two forward slashesRegular expressions are put between two forward slashes(/) and escaped with a backward slash (\).(/) and escaped with a backward slash (\).

    Special characters (that need to be escaped to be matched)Special characters (that need to be escaped to be matched)are:are:

    . | ( ) [ ] { } + \ ^ $ * ?.. | ( ) [ ] { } + \ ^ $ * ?. Ex:Ex:

    data = "Programming in Ruby"data = "Programming in Ruby"

    if data =~ /^P/ || data =~ /ming$/if data =~ /^P/ || data =~ /ming$/

    data.gsub!(/[pr]/i, 'X')data.gsub!(/[pr]/i, 'X')print "#{data}\n"print "#{data}\n"

    endend

  • 7/28/2019 Rubyonrails(1,2) Imp

    12/56

    Regular ExpressionsRegular Expressions

    In Ruby, a regular expression is written in the form of /pattern/modifiersIn Ruby, a regular expression is written in the form of /pattern/modifierswhere "pattern" is the regular expression itself, and "modifiers" are a series ofwhere "pattern" is the regular expression itself, and "modifiers" are a series ofcharacters indicating various options. The "modifiers" part is optional. Thischaracters indicating various options. The "modifiers" part is optional. Thissyntax is borrowed from Perl. Ruby supports the following modifiers:syntax is borrowed from Perl. Ruby supports the following modifiers:

    /i makes the regex match case insensitive./i makes the regex match case insensitive.

    /m makes the dot match newlines. Ruby indeed uses /m, whereas Perl and/m makes the dot match newlines. Ruby indeed uses /m, whereas Perl andmany other programming languages use /s for "dot matches newlines".many other programming languages use /s for "dot matches newlines".

    /x tells Ruby to ignore whitespace between regex tokens./x tells Ruby to ignore whitespace between regex tokens. /o causes any #{...} substitutions in a particular regex literal to be performed/o causes any #{...} substitutions in a particular regex literal to be performed

    just once, the first time it is evaluated. Otherwise, the substitutions will bejust once, the first time it is evaluated. Otherwise, the substitutions will beperformed every time the literal generates a Regexp object.performed every time the literal generates a Regexp object.

    You can combine multiple modifiers by stringing them together as in /regex/is.You can combine multiple modifiers by stringing them together as in /regex/is. In Ruby, the caret and dollar always match before and after newlines. RubyIn Ruby, the caret and dollar always match before and after newlines. Rubydoes not have a modifier to change this. Use \A and \Z to match at the start ordoes not have a modifier to change this. Use \A and \Z to match at the start orthe end of the string.the end of the string.

    Since forward slashes delimit the regular expression, any forward slashes thatSince forward slashes delimit the regular expression, any forward slashes thatappear in the regex need to be escaped. E.g. the regex 1/2 is written as /1\/2/appear in the regex need to be escaped. E.g. the regex 1/2 is written as /1\/2/in Ruby.in Ruby.

  • 7/28/2019 Rubyonrails(1,2) Imp

    13/56

    Ruby Methods:Ruby Methods:

    A method returns the value of the last lineA method returns the value of the last line

    Methods that act as queries are often named with a trailing ?Methods that act as queries are often named with a trailing ? Methods that are "dangerous," or modify the receiver, might be namedMethods that are "dangerous," or modify the receiver, might be named

    with a trailing ! (Bang methods)with a trailing ! (Bang methods)

    # A simple method# A simple method

    def hellodef hello

    puts 'Hello'puts 'Hello'

    endend

    #use the method#use the method

    hellohello

    # Method with an argument - 1# Method with an argument - 1

    def hello1(name)def hello1(name)

    puts 'Hello ' + nameputs 'Hello ' + name

    return 'success'return 'success'

    endend

    puts(hello1('satish'))puts(hello1('satish'))

  • 7/28/2019 Rubyonrails(1,2) Imp

    14/56

    Sample programSample program

    def fact(n)if n == 0

    1else

    n * fact(n-1)end

    end

    puts "Enter number"c=getsn=c.to_i

    puts "Factorial of #{n} is #{fact(n)}"

  • 7/28/2019 Rubyonrails(1,2) Imp

    15/56

    Exception HandlingException Handling

    beginbegin

    x=3/0x=3/0

    puts xputs x

    rescue ArgumentErrorrescue ArgumentErrorputs "wrong no of arguments"puts "wrong no of arguments"

    rescue ZeroDivisionErrorrescue ZeroDivisionError

    puts "division by zero is illegalputs "division by zero is illegal

    rescuerescueputs "There is some unknown exception"puts "There is some unknown exception"

    endend

  • 7/28/2019 Rubyonrails(1,2) Imp

    16/56

    Exception HandlingException Handling

    def Division(x,y)def Division(x,y)

    if(y==0)if(y==0)

    raiseexceptionraiseexception

    endend

    z=x/yz=x/y

    puts zputs z

    endenddef raiseexceptiondef raiseexception

    beginbegin

    puts 'There is an error:'puts 'There is an error:'

    raiseraise

    rescuerescue

    puts 'Division by Zero is Illegal'puts 'Division by Zero is Illegal'

    endendexit(1)exit(1)

    endend

    Division(4,0)Division(4,0)

    Output:There is an error:Division by Zero is Illegal

  • 7/28/2019 Rubyonrails(1,2) Imp

    17/56

    ARRAYSARRAYS

    The class Array holds a collection of objectThe class Array holds a collection of object

    references. Each object reference occupies areferences. Each object reference occupies a

    position in the array, identified by a non-negativeposition in the array, identified by a non-negative

    integer index.integer index.

    You can create arrays using literals or by explicitlyYou can create arrays using literals or by explicitly

    creating an Array object. A literal array is simply acreating an Array object. A literal array is simply a

    list of objects between square brackets.list of objects between square brackets.

    E l f AE l f A

  • 7/28/2019 Rubyonrails(1,2) Imp

    18/56

    Example for ArraysExample for ArraysEX1:EX1:

    a = [ 3.14159, "pie", 99 ]a = [ 3.14159, "pie", 99 ]

    a.type Arraya.type Array

    a.length 3a.length 3

    a[0] 3.14159a[0] 3.14159

    a[1] "pie"a[1] "pie"

    a[2] 99a[2] 99

    a[3] nila[3] nil

    EX2:EX2:

    b = Array.newb = Array.new

    b[0] = 1b[0] = 1

    b[1] = 4b[1] = 4

    puts b [1,4]puts b [1,4]b.sort (or) b.reverseb.sort (or) b.reverse

    puts bputs b

  • 7/28/2019 Rubyonrails(1,2) Imp

    19/56

    Array usageArray usage

    b=Array.newb[0]=1b[1]=2

    b.push 3b.push 4b.push 5b.push 6

    puts "Satck elements are: "puts b

    b.popb.pop

    puts "after pop Stack elements:"puts b

    b=Array.newb[0]=1b[1]=2

    b

  • 7/28/2019 Rubyonrails(1,2) Imp

    20/56

    HashesHashes

    Hashes (sometimes known as associative arrays or dictionaries) areHashes (sometimes known as associative arrays or dictionaries) are

    similar to arrays, in that they are indexed collectives of objectsimilar to arrays, in that they are indexed collectives of objectreferences.references.

    However, while you index arrays with integers, you can index aHowever, while you index arrays with integers, you can index ahash with objects of any type: strings, regular expressions, and sohash with objects of any type: strings, regular expressions, and soon. When you store a value in a hash, you actually supply twoon. When you store a value in a hash, you actually supply two

    objects---the key and the value. You can subsequently retrieve theobjects---the key and the value. You can subsequently retrieve thevalue by indexing the hash with the same key. The values in a hashvalue by indexing the hash with the same key. The values in a hashcan be any objects of any type.can be any objects of any type.

    The example that follows uses hash literals: a list ofThe example that follows uses hash literals: a list ofkeykey=>=> valuevaluepairs between braces.pairs between braces.

    Compared with arrays, hashes have one significant advantage:Compared with arrays, hashes have one significant advantage:they can use any object as an index. However, they also have athey can use any object as an index. However, they also have asignificant disadvantage: their elements are not ordered, so yousignificant disadvantage: their elements are not ordered, so youcannot easily use a hash as a stack or a queue.cannot easily use a hash as a stack or a queue.

  • 7/28/2019 Rubyonrails(1,2) Imp

    21/56

    Example for HashExample for HashEX1:EX1:

    h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }

    Puts h.length 3Puts h.length 3

    Puts h['dog'] "canine"Puts h['dog'] "canine"Puts h['cow'] = 'bovine'Puts h['cow'] = 'bovine'

    h[12] = 'dodecine'h[12] = 'dodecine'

    h['cat'] = 99h['cat'] = 99

    h.delete(dog)h.delete(dog)

    Puts h {"cow"=>"bovine", "cat"=>99,12=>"dodecine, "donkey"=>"asinine"}Puts h {"cow"=>"bovine", "cat"=>99,12=>"dodecine, "donkey"=>"asinine"}

    EX2:EX2:

    people = Hash.newpeople = Hash.new

    people[:nickname] = 'IndianGuru'people[:nickname] = 'IndianGuru'

    people[:language] = 'Marathi'people[:language] = 'Marathi'people[:lastname] = 'Tamil'people[:lastname] = 'Tamil'

    puts people[:lastname] # Tamilputs people[:lastname] # Tamil

  • 7/28/2019 Rubyonrails(1,2) Imp

    22/56

    Operations on HashOperations on Hash

    names = {"Jack" => "Ruby", "Monty" => "python",names = {"Jack" => "Ruby", "Monty" => "python",

    "Blaise"=>"Pascal", "Minnie"=>"Perl"}"Blaise"=>"Pascal", "Minnie"=>"Perl"}

    list=names.sortlist=names.sort

    puts listputs list

    puts " \nOne elenent in list:\n "puts " \nOne elenent in list:\n "

    puts list[3][1]puts list[3][1]

  • 7/28/2019 Rubyonrails(1,2) Imp

    23/56

    Creating a Hash from an ArrayCreating a Hash from an Array

    array = [2,3,4,5,6,7,8,9]array = [2,3,4,5,6,7,8,9]

    hash=Hash[*array]hash=Hash[*array]

    #hash is now: {2=>3, 4=>5, 6=>7, 8=>9}#hash is now: {2=>3, 4=>5, 6=>7, 8=>9}

    Merging two HashesMerging two Hashes

    h1={base=>foundation, pedestal=>base}h1={base=>foundation, pedestal=>base}

    h2={base=>non-acid, salt=>NaCl}h2={base=>non-acid, salt=>NaCl}

    H3 = h1.merge(h2) { |key,old,new| old < new ? old : new }H3 = h1.merge(h2) { |key,old,new| old < new ? old : new }

    Output:Output:

    H3 =>H3 =>

    {salt=>NaCl, pedestal=>base, base=>foundation}{salt=>NaCl, pedestal=>base, base=>foundation}

    Operaions on Hash

  • 7/28/2019 Rubyonrails(1,2) Imp

    24/56

    IteratorsIterators

    An iterator is a special kind of method. It is a methodAn iterator is a special kind of method. It is a methodthat lets you access items one at a time.that lets you access items one at a time.

    Arrays are not the only objects that have iterators, butArrays are not the only objects that have iterators, butthe are one of the most important. Iterators are best seenthe are one of the most important. Iterators are best seenthrough an example. Here we use Array#eachthrough an example. Here we use Array#each

  • 7/28/2019 Rubyonrails(1,2) Imp

    25/56

    Example for IteratorExample for Iterator

    friends = ["Melissa", "Jeff", "Ashley", Rob]friends = ["Melissa", "Jeff", "Ashley", Rob]

    friends.each do |friend|friends.each do |friend|

    puts "I have a friend called " + friendputs "I have a friend called " + friend

    endend

    Output:Output:

    I have a friend called MelissaI have a friend called Melissa

    I have a friend called JeffI have a friend called JeffI have a friend called AshleyI have a friend called Ashley

    I have a friend called RobI have a friend called Rob

  • 7/28/2019 Rubyonrails(1,2) Imp

    26/56

    Iterator for HashIterator for Hash

    names = {"W" => 666 , "X" => 777,names = {"W" => 666 , "X" => 777,

    "Y"=>888, "Z"=>999}"Y"=>888, "Z"=>999}

    names.each do |key,val|names.each do |key,val|

    print key, " value is ", val, ";\n"print key, " value is ", val, ";\n"

    endend

    Output:Output:

    W value is 666;W value is 666;

    X value is 777;X value is 777;Y value is 888;Y value is 888;

    Z value is 999;Z value is 999;

  • 7/28/2019 Rubyonrails(1,2) Imp

    27/56

    RangesRanges

    digits=0..9digits=0..9

    sclae=09sclae=09

    The operator .. is inclusive its endpoint. AndThe operator .. is inclusive its endpoint. And

    the operator is exclusive of its end point.the operator is exclusive of its end point.

    r1= 3..6 #closedr1= 3..6 #closed

    r2=36 #openr2=36 #open

    a1=r1.to_a #{3,4,5,6}a1=r1.to_a #{3,4,5,6}

    a2=r2.to_a #{3,4,5}a2=r2.to_a #{3,4,5}

  • 7/28/2019 Rubyonrails(1,2) Imp

    28/56

    Operations on RangesOperations on Ranges

    Iterating over rangesIterating over ranges

    (3..6).each {|x| puts x }(3..6).each {|x| puts x }

    Membership testingMembership testingr1=23456..34567r1=23456..34567

    x=141142x=141142

    y=31416y=31416

    r1.include?(x) #falser1.include?(x) #false

    r1.include?(y) #truer1.include?(y) #true

  • 7/28/2019 Rubyonrails(1,2) Imp

    29/56

    Working with FilesWorking with Files

    # Create a new file and write to it# Create a new file and write to it

    File.open('testfile.rb', 'w') do |f2|File.open('testfile.rb', 'w') do |f2|

    # use "\n" for two lines of text# use "\n" for two lines of text

    f2.puts "Created by Suresh\nThank God!"f2.puts "Created by Suresh\nThank God!"

    endend

    File.open('getfile.rb', 'w') do |f2|File.open('getfile.rb', 'w') do |f2|

    File.open('testfile.rb', 'r') do |f1|File.open('testfile.rb', 'r') do |f1|

    while line = f1.getswhile line = f1.gets

    puts lineputs line

    f2.write(line)f2.write(line)

    endendendend

    endend

  • 7/28/2019 Rubyonrails(1,2) Imp

    30/56

    ThreadsThreads

    Ruby threads are user-level threads and areRuby threads are user-level threads and areoperating system independent.operating system independent.

    Ex:Ex:

    thread = Thread.new dothread = Thread.new do

    puts hiputs hi

    endend

  • 7/28/2019 Rubyonrails(1,2) Imp

    31/56

    Accessing thread variablesAccessing thread variables

    a=3a=3b=4b=4

    c=5c=5

    puts aputs a

    thread = Thread.new(a,b,c) do |a,x,y|thread = Thread.new(a,b,c) do |a,x,y|

    a=4a=4x=89x=89

    y=88y=88

    thread[:f] = 34thread[:f] = 34

    endend

    puts aputs aputs ""puts ""

    puts thread[:f]puts thread[:f]

  • 7/28/2019 Rubyonrails(1,2) Imp

    32/56

    Thread - statusThread - status

    t1 = Thread.new { loop { } }t1 = Thread.new { loop { } }t2 = Thread.new { sleep 5 }t2 = Thread.new { sleep 5 }

    t3 = Thread.new { Thread.stop }t3 = Thread.new { Thread.stop }

    t4 = Thread.new { raise exceptionsss }t4 = Thread.new { raise exceptionsss }

    t5 = Thread.new { Thread.exit }t5 = Thread.new { Thread.exit }

    puts "Thread t1 status: #{t1.status}"puts "Thread t1 status: #{t1.status}"

    puts "Thread t2 status: #{t2.status}"puts "Thread t2 status: #{t2.status}"puts "Thread t3 status: #{t3.status}"puts "Thread t3 status: #{t3.status}"

    puts "Thread t4 status: #{t4.status}"puts "Thread t4 status: #{t4.status}"

    puts "Thread t5 status: #{t5.status}"puts "Thread t5 status: #{t5.status}"

  • 7/28/2019 Rubyonrails(1,2) Imp

    33/56

    Synchronizing ThreadsSynchronizing Threads

    x=0x=0

    t1= Thread.new dot1= Thread.new do1.upto(1000) do1.upto(1000) do

    Thread.critical = trueThread.critical = true

    x = x+1x = x+1

    Thread.critical = falseThread.critical = false

    endend

    endend

    t2= Thread.new dot2= Thread.new do

    1.upto(1000) do1.upto(1000) do

    Thread.critical = trueThread.critical = true

    x = x+1x = x+1

    Thread.critical = falseThread.critical = falseendend

    endend

    t1.joint1.join

    t2.joint2.join

    puts xputs x

    Synchronizing ThreadsSynchronizing Threads

  • 7/28/2019 Rubyonrails(1,2) Imp

    34/56

    Synchronizing ThreadsSynchronizing Threadsrequire 'thread'require 'thread'

    mutex = Mutex.newmutex = Mutex.new

    cv = ConditionVariable.newcv = ConditionVariable.new

    a = Thread.new {a = Thread.new {

    mutex.synchronize {mutex.synchronize {

    puts "A: I have critical section, but will wait for cv"puts "A: I have critical section, but will wait for cv"

    cv.wait(mutex)cv.wait(mutex)

    puts "A: I have critical section again! I rule!"puts "A: I have critical section again! I rule!"

    }}}}

    puts "(Later, back at the ranch...)"puts "(Later, back at the ranch...)"

    b = Thread.new {b = Thread.new {

    mutex.synchronize {mutex.synchronize {

    puts "B: Now I am critical, but am done with cv"puts "B: Now I am critical, but am done with cv"

    cv.signalcv.signal

    puts "B: I am still critical, finishing up"puts "B: I am still critical, finishing up"

    }}

    }}

    a.joina.join

    b.joinb.join

  • 7/28/2019 Rubyonrails(1,2) Imp

    35/56

    22ndnd

    DayDay

  • 7/28/2019 Rubyonrails(1,2) Imp

    36/56

    OOPS & DYNAMIC FEATURESOOPS & DYNAMIC FEATURES

    Cl d Obj tCl d Obj t

  • 7/28/2019 Rubyonrails(1,2) Imp

    37/56

    Classes and ObjctsClasses and Objctsclass Firstclass First

    def initialize()def initialize()@x =786@x =786

    endend

    def wishdef wish

    puts "Hello world"puts "Hello world"

    puts @xputs @xendend

    endend

    s = First.news = First.news.wishs.wish

    Ruby Access ControlRuby Access Control

  • 7/28/2019 Rubyonrails(1,2) Imp

    38/56

    Ruby Access ControlRuby Access Control The only easy way to change an object's state in Ruby is by calling one of itsThe only easy way to change an object's state in Ruby is by calling one of its

    methods. Control access to the methods, and you have controlled access to themethods. Control access to the methods, and you have controlled access to theobject. A good rule of the thumb is never to expose methods that could leave anobject. A good rule of the thumb is never to expose methods that could leave anobject in an invalid state.object in an invalid state.

    Ruby gives you three levels of protection:Ruby gives you three levels of protection:

    PublicPublic methods can be called by everyone - no access control is enforced. Amethods can be called by everyone - no access control is enforced. Aclass's instance methods (these do not belong only to one object; instead, everyclass's instance methods (these do not belong only to one object; instead, every

    instance of the class can call them) are public by default; anyone can call them.instance of the class can call them) are public by default; anyone can call them.TheThe initializeinitialize method is always private.method is always private.

    ProtectedProtected methods can be invoked only by objects of the defining class and itsmethods can be invoked only by objects of the defining class and itssubclasses. Access is kept within the family.subclasses. Access is kept within the family.

    PrivatePrivate methods cannot be called with an explicit receiver - the receiver ismethods cannot be called with an explicit receiver - the receiver isalwaysalways selfself. This means that private methods can be called only in the context. This means that private methods can be called only in the contextof the current object; you cannot invoke another object's private methods.of the current object; you cannot invoke another object's private methods.

    Access control is determined dynamically, as the program runs, not statically.Access control is determined dynamically, as the program runs, not statically.You will get an access violation only when the code attempts to execute theYou will get an access violation only when the code attempts to execute therestricted method.restricted method.

  • 7/28/2019 Rubyonrails(1,2) Imp

    39/56

    Access Control Example:Access Control Example:

    classclass ClassAccessClassAccess

    defdefm1m1 # this method is public# this method is public

    endendprotectedprotected

    defdefm2m2 # this method is protected# this method is protected

    endendprivateprivate

    defdefm3m3 # this method is private# this method is private

    endendendendca = ClassAccess.ca = ClassAccess.newnewca.m1ca.m1

    ca.m2ca.m2

    ca.m3ca.m3

    Alternatively, you can set access levels of named methods by listing them as arguments to the accessAlternatively, you can set access levels of named methods by listing them as arguments to the accesscontrol functions.control functions.

    classclass ClassAccessClassAccessdefdefm1m1 # this method is public# this method is public

    endendpublic :m1public :m1

    protected :m2, :m3protected :m2, :m3

    private :m4, :m5private :m4, :m5

    endend

  • 7/28/2019 Rubyonrails(1,2) Imp

    40/56

    An example for 'protected' access control:An example for 'protected' access control:

    classclass PersonPerson

    defdefinitialize(age)initialize(age)@age = age@age = age

    endenddefdefageage

    @age@age

    endenddefdefcompare_age(c)compare_age(c)

    ififc.age > agec.age > age"The other object's age is bigger.""The other object's age is bigger."

    elseelse"The other object's age is the same or smaller.""The other object's age is the same or smaller."

    endendendendprotected :ageprotected :age

    endend

    chris = Person.chris = Person.newnew(25)(25)

    marcos = Person.marcos = Person.newnew(34)(34)

    putsputs chris.compare_age(marcos)chris.compare_age(marcos)

    The output is:The output is:

    The other object's age is biggerThe other object's age is bigger ..

  • 7/28/2019 Rubyonrails(1,2) Imp

    41/56

    Accessor methodsAccessor methods

    Encapsulation is achieved when the instanceEncapsulation is achieved when the instancevariables are private to an object and you havevariables are private to an object and you have

    public getters and setters (in Ruby, we callpublic getters and setters (in Ruby, we call

    them attribute readers and attribute writers).them attribute readers and attribute writers).

    To make instance variables available, RubyTo make instance variables available, Ruby

    provides accessor methods that return theirprovides accessor methods that return theirvalues.values.

    E l f A Att ib tE l f A Att ib t

  • 7/28/2019 Rubyonrails(1,2) Imp

    42/56

    Example for Accessor AttributesExample for Accessor Attributes# First without accessor methods# First without accessor methods

    classclass SongSongdefdefinitialize(name, artist)initialize(name, artist)

    @name = name@name = name

    @artist = artist@artist = artist

    endenddefdefnamename

    @name@name

    endenddefdefartistartist

    @artist@artist

    endendendend

    song = Song.song = Song.newnew("Brazil", "Ivete")("Brazil", "Ivete")putsputs song.namesong.name

    putsputs song.artistsong.artist

    # Now, with accessor methods# Now, with accessor methods

    classclass SongSong

    defdef initialize(name, artist)initialize(name, artist)

    @name = name@name = name

    @artist = artist@artist = artist

    endend

    attr_reader :name, :artistattr_reader :name, :artist# For creating reader and writer methods# For creating reader and writer methods

    # attr_accessor :name# attr_accessor :name

    # For creating writer methods# For creating writer methods

    # attr_writer :name# attr_writer :name

    endend

    song = Song.song = Song.newnew("Brazil", "Ivete Sangalo")("Brazil", "Ivete Sangalo")

    putsputs song.namesong.name

    putsputs song.artistsong.artist

    InheritanceInheritance

  • 7/28/2019 Rubyonrails(1,2) Imp

    43/56

    InheritanceInheritance Inheritance is a relation between two classes. WeInheritance is a relation between two classes. We

    know that all cats are mammals, and all mammals areknow that all cats are mammals, and all mammals areanimals. The benefit of inheritance is that classesanimals. The benefit of inheritance is that classeslower down the hierarchy get the features of thoselower down the hierarchy get the features of thosehigher up, but can also add specific features of theirhigher up, but can also add specific features of theirown. If all mammals breathe, then all cats breathe.own. If all mammals breathe, then all cats breathe.

    In Ruby, a class can only inherit from a single otherIn Ruby, a class can only inherit from a single otherclass. Some other languages support multipleclass. Some other languages support multiple

    inheritance, a feature that allows classes to inheritinheritance, a feature that allows classes to inheritfeatures from multiple classes, but Ruby doesn'tfeatures from multiple classes, but Ruby doesn'tsupport this.support this.

    Inheritance ExampleInheritance Example

  • 7/28/2019 Rubyonrails(1,2) Imp

    44/56

    Inheritance ExampleInheritance Exampleclass Mammalclass Mammal

    def breathedef breathe

    puts "inhale and exhale"puts "inhale and exhale"endend

    endend

    class Cat < Mammalclass Cat < Mammaldef speakdef speak

    puts "Meow"puts "Meow"

    endend

    endend

    rani = Cat.newrani = Cat.new

    rani.breatherani.breathe

    rani.speakrani.speak

    E l f i h iE l f i h it

  • 7/28/2019 Rubyonrails(1,2) Imp

    45/56

    Example for inheritanceExample for inheritanceclassclass BirdBird

    defdefpreenpreen

    putsputs "I am cleaning my feathers.""I am cleaning my feathers."endenddefdefflyfly

    putsputs "I am flying.""I am flying."

    endendendend

    classclass Penguin < BirdPenguin < Birddefdefflyfly

    putsputs "Sorry. I'd rather swim.""Sorry. I'd rather swim."

    endendendend

    p = Penguin.p = Penguin.newnewp.preenp.preen

    p.flyp.fly

    Multiple InheritanceMultiple Inheritance

  • 7/28/2019 Rubyonrails(1,2) Imp

    46/56

    Multiple InheritanceMultiple Inheritance

    module SmallModulemodule SmallModule

    def hellodef hello

    puts "Hello....small"puts "Hello....small"endend

    def adddef add

    puts "Called add method of SmallModule"puts "Called add method of SmallModule"

    endend

    endend

    class MultipleInherclass MultipleInherinclude BigModuleinclude BigModule

    include SmallModuleinclude SmallModule

    def hellodef hello

    supersuper

    puts "Hello..Suresh"puts "Hello..Suresh"

    endendendend

    s = MultipleInher.news = MultipleInher.new

    s.hellos.hello

    s.adds.add

    s.dels.del

    module BigModulemodule BigModule

    def deldef del

    puts "Called del method of BigModule"puts "Called del method of BigModule"endend

    def hellodef hello

    puts "Hello...big"puts "Hello...big"

    endend

    endend

    Output:

    Hello....smallHello..SureshCalled add method of SmallModuleCalled del method of BigModule

    Method overloadingMethod overloading

  • 7/28/2019 Rubyonrails(1,2) Imp

    47/56

    Method overloadingMethod overloading

    You want to create two different versions of aYou want to create two different versions of a

    method with the same name: two methods thatmethod with the same name: two methods thatdiffer in the arguments they take. However,differ in the arguments they take. However, aaRuby class can have only one method with aRuby class can have only one method with agiven namegiven name. Within that single method, though,. Within that single method, though,

    you can put logic that branches depending onyou can put logic that branches depending onhow many and what kinds of objects werehow many and what kinds of objects werepassed in as arguments.passed in as arguments.

    Example for Method overloadingExample for Method overloading

  • 7/28/2019 Rubyonrails(1,2) Imp

    48/56

    Example for Method overloadingExample for Method overloadingclass Rectangleclass Rectangle

    def initialize(*args)def initialize(*args)

    if args.size < 2 || args.size > 3if args.size < 2 || args.size > 3

    raiseexceptionraiseexception

    elseelseif args.size == 2if args.size == 2

    @@x = 2@@x = 2

    puts 'Two arguments'puts 'Two arguments'

    elseelse

    @@x =3@@x =3

    puts 'Three arguments'puts 'Three arguments'

    endendendend

    endend

    def Areadef Area

    puts @@xputs @@x

    endend

    def raiseexceptiondef raiseexceptionbeginbegin

    puts 'There is an error:'puts 'There is an error:'

    raiseraise

    rescuerescue

    puts 'Agguments must be either 2 or 3'puts 'Agguments must be either 2 or 3'

    endend

    endend

    C ti dC ti d

  • 7/28/2019 Rubyonrails(1,2) Imp

    49/56

    Continued..Continued..a = Rectangle.new([10, 23], 4, 10)a = Rectangle.new([10, 23], 4, 10)

    b= Rectangle.new([10, 23], [14, 13])b= Rectangle.new([10, 23], [14, 13])

    a.Areaa.Area

    c= Rectangle.new(14)c= Rectangle.new(14)

    Output:Output:

    >ruby class.rb>ruby class.rbThree argumentsThree arguments

    Two argumentsTwo arguments

    22

    There is an error:There is an error:

    Arguments must be either 2 or 3Arguments must be either 2 or 3

    >Exit code: 0>Exit code: 0

    Method OverridingMethod Overriding

  • 7/28/2019 Rubyonrails(1,2) Imp

    50/56

    Method OverridingMethod OverridingIn object oriented programming, is a language feature that allows aIn object oriented programming, is a language feature that allows asubclass to provide a specific implementation of a method that is alreadysubclass to provide a specific implementation of a method that is alreadyprovided by one of its superclasses. The implementation in the subclassprovided by one of its superclasses. The implementation in the subclass

    overrides (replaces) the implementation in the superclass.overrides (replaces) the implementation in the superclass.

    Here's an example:Here's an example:

    classclass AA

    defdefaa

    putsputs 'In class A''In class A'endend

    endend

    classclass B < AB < A

    defdefaa

    putsputs 'In class B''In class B'endend

    endend

    b = B.b = B.newnewb.ab.a

    Usage of superUsage of super

  • 7/28/2019 Rubyonrails(1,2) Imp

    51/56

    Usage of superUsage of super

    The wayThe way supersuper handles arguments is as follows:handles arguments is as follows:

    When you invokeWhen you invoke supersuper with no arguments Ruby sends a messagewith no arguments Ruby sends a messageto the parent of the current object, asking it to invoke a method ofto the parent of the current object, asking it to invoke a method ofthe same name as the method invokingthe same name as the method invoking supersuper. It automatically. It automaticallyforwards the arguments that were passed to the method fromforwards the arguments that were passed to the method fromwhich it's called.which it's called.

    Called with an empty argument list -Called with an empty argument list - super()super()-it sends no-it sends noarguments to the higher-up method, even if arguments were passedarguments to the higher-up method, even if arguments were passedto the current method.to the current method.

    Called with specific arguments -Called with specific arguments - super(a, b, c)super(a, b, c) - it sends exactly- it sends exactly

    those arguments.those arguments.

    Example for super usageExample for super usage

  • 7/28/2019 Rubyonrails(1,2) Imp

    52/56

    Example for super usageExample for super usage classclass BicycleBicycle

    attr_reader :gears, :wheels, :seatsattr_reader :gears, :wheels, :seats

    defdefinitialize(gears = 1)initialize(gears = 1)

    @wheels = 2@wheels = 2

    @seats = 1@seats = 1

    @gears = gears@gears = gears

    endendendendclassclass Tandem < BicycleTandem < Bicycle

    defdefinitialize(gears)initialize(gears)supersuper@seats = 2@seats = 2

    endendendendt = Tandem.t = Tandem.newnew(2)(2)

    putsputs t.gearst.gearsputsputs t.wheelst.wheels

    putsputs t.seatst.seats

    b = Bicycle.b = Bicycle.newnewputsputs b.gearsb.gears

    putsputs b.wheelsb.wheels

    putsputs b.seatsb.seats

    The output is:The output is:

    22

    22

    22

    11

    22

    11

  • 7/28/2019 Rubyonrails(1,2) Imp

    53/56

    Dynamic Features of RubyDynamic Features of Ruby

    Dynamic typingDynamic typing

    Coding at run timeCoding at run time

    ReflectionReflection Missing methodsMissing methods

    Garbage collectionGarbage collection

  • 7/28/2019 Rubyonrails(1,2) Imp

    54/56

    Coding at runtimeCoding at runtime

    def calculate(op1,operator,op2)def calculate(op1,operator,op2)str = op1.to_s + operator + op2.to_sstr = op1.to_s + operator + op2.to_s

    eval(str)eval(str)

    endend

    puts calculate(2,"*",3)puts calculate(2,"*",3)puts calculate(2,+",3)puts calculate(2,+",3)

    puts calculate(2,-",3)puts calculate(2,-",3)

    Output:Output:

    6655

    -1-1

    R b D i M h dR b D i M th d

  • 7/28/2019 Rubyonrails(1,2) Imp

    55/56

    Ruby Dynamic MethodsRuby Dynamic Methods

    Has a feature call method missing, which allows yourHas a feature call method missing, which allows your

    class to react to unknown method calls withoutclass to react to unknown method calls withoutraising a unknown-method error.raising a unknown-method error.

    This allows a class to answer to whatever method isThis allows a class to answer to whatever method is

    called. Which is very useful if you are writing a Rubycalled. Which is very useful if you are writing a Rubybinding to a component you query also dynamically,binding to a component you query also dynamically,because with this way method_missing act as abecause with this way method_missing act as agateway only, forwarding the message (methodgateway only, forwarding the message (methodname) and the parameters, after doing thename) and the parameters, after doing the

    appropiate conversion.appropiate conversion.

    M th d i i E lM th d i i E l

  • 7/28/2019 Rubyonrails(1,2) Imp

    56/56

    Method_missing ExampleMethod_missing Example

    class Dynamicclass Dynamic

    def hello(str)def hello(str)puts "Hello " + strputs "Hello " + str

    endend

    def method_missing(*args)def method_missing(*args)

    str = args[0].to_sstr = args[0].to_sputs str + " method is unavailable."puts str + " method is unavailable."

    endend

    endend

    r= Dynamic.newr= Dynamic.newr.hello('suresh')r.hello('suresh')

    r.addr.addOutput:

    Hello suresh

    Add method is unavailable.