170 likes | 253 Views
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.
E N D
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 • “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
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
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
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
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
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
Access Control ..continued • 2nd Method: class MyClass def method1 end # other methods public : method1, :method2 private : method3 protected : method4 end
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
Container, Blocks and Iterators Sudheer Gupta Bysani
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”
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 }
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
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" }
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
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 "