1 / 17

Classes, Objects, And Variables

Classes, Objects, And Variables. Sudheer Gupta Bysani. Class definition & instantiation . Use keyword “class” Class definition ends by keyword “end” Instantiation : OneSong = Song.new. #class definition example class Song # methods goes here # …. end. Constructors in ruby.

kalani
Download Presentation

Classes, Objects, And Variables

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Classes, Objects, And Variables Sudheer Gupta Bysani

  2. Class definition & instantiation • Use keyword “class” • Class definition ends by keyword “end” • Instantiation : OneSong = Song.new #class definition example class Song # methods goes here # …. end

  3. Constructors in ruby • “initialize” method is used • Member variables start with @ Eg: @name class Song def initialize(name, artist, duration) @name     = name      @artist   = artist      @duration = duration    end end

  4. Attributes : Readable & Writable • Readable : return values of instance variables • Writable : assign values to instance variables class Song attr_reader :name, :artist, :duration attr_writer :duration # note : no “@” for attributes def initialize(name,artist,duration) # …. end end aSong = Song.new("Bicylops", "Fleck", 260) aSong.duration >> 260 aSong.duration = 257 aSong.duration >> 257

  5. Virtual Attributes • Wrappers around an object’s instance variables • Eg: to access duration in minutes class Song def durationInMinutes @duration/60.0   # force floating point end def durationInMinutes=(value) @duration = (value*60).to_i end end

  6. Inheritance • Use “<“ to derive from base class • Use “super” to call the base call initializer class KaraokeSong < Song def initialize(name, artist, duration, lyrics) super(name, artist, duration) @lyrics = lyrics end end

  7. Class variables & Class Method • Just like static variables in C++ • Starts with “@@” Eg : @@num_songs • By default, private to the class • accessor method to be written explicitly to be accessible to outside world. • Accessor method could be instance method or class method • Class Methods definition preceded by class name eg: def Song.class_method # .. end

  8. Access Control • Two ways to specify access levels of methods • 1st Method: Similar to C++ • class MyClass • def method1 # default is public • end • Private #subsequent methods are private • def method2 • end • Protected #subsequent methods are protected • def method3 • end

  9. Access Control ..continued • 2nd Method: class MyClass def method1 end # other methods public : method1, :method2 private : method3 protected : method4 end

  10. Protected Access • Used when objects need to access internal state of other objects class Account    attr_reader :balance       # accessor method 'balance'    protected :balance         # and make it protected # need a reader attribute and still not accessible to outside world def greaterBalanceThan(other)      return @balance > other.balance    end end

  11. Container, Blocks and Iterators Sudheer Gupta Bysani

  12. Arrays • Holds a collection of object references • 2 ways to create arrays • 1st Method: a = [3.14, “pie”, 99 ] a.Class  Array a.Length  3 A[0]  3.14 • 2nd Method: b = Array.new b[0] = 3.14 b[1] = “pie”

  13. Handy ways of using an Array • a[-1]  returns last element • a[-2]  returns last but one element • a[1 , 3]  [start, count] • a[1..3]  [start, end] • Concatenation : [1, 2,3] + [4,5]  [1,2,3,4,5] • Difference : [1,1,1,2,3,2,4,5] – [1,2]  [3,4,5] Removes all the occurrences • Append : [1,2] << “c” << “d” << [4,5]  [1,2,”c”,”d”,4,5] • Equality : [“a”, “b”] == [“a”,”c”]  false • Clear : a.clear # removes all the elements of the array • Each : a.each { |x| puts x }

  14. Hashes • Associate arrays/maps/dictionaries • h = { “dog” => “canine, “cat” => “feline” } • h.length  2 • h[“dog”]  “canine” • h[“cow”] = “bovine” • h.each { |key, value| puts “#{key} is #{value}” } • Calls block once for each key, passing key and value as parameters • h.each_key { |key| puts key } • Calls block once for each key • Merge, has_key, has_value, invert methods available

  15. Blocks and Iterators • Iterator : a method that invokes block of code repeatedly eg: def fibUpTo(max)    i1, i2 = 1, 1         # parallel assignment    while i1 <= max      yield i1      i1, i2 = i2, i1+i2    end end fibUpTo(1000) { |f| print f, " " } def threeTimes    yield    yield    yield end threeTimes { puts "Hello" }

  16. Find method .... Using iterator • A block may also return a value to the method class Array    def find      for i in 0...size        value = self[i]        return value if yield(value)      end      return nil    end end [1, 3, 5, 7, 9].find {|v| v*v > 30 }  7 # Block returns true if v*v > 30

  17. Blocks as Closures • Code block as Proc Object • Use Proc#call method to invoke the block • Proc object carries all the context in which block was defined. In below case, its on method nTimes def nTimes(aThing)    return lambda { |n| aThing * n } end p1 = nTimes(23) p1.call(3)  69 p1.call(4)  92 p2 = nTimes("Hello ") p2.call(3)  Hello Hello Hello "

More Related