Ruby Objects, Classes and Variables - PowerPoint PPT Presentation

1 / 21
About This Presentation
Title:

Ruby Objects, Classes and Variables

Description:

Song:0x401b2a14 ... All methods of Song are included in KaraokeSong ... class KaraokeSong Song. def initialize(name, artist, duration, lyrics) ... – PowerPoint PPT presentation

Number of Views:46
Avg rating:3.0/5.0
Slides: 22
Provided by: Michael1759
Category:

less

Transcript and Presenter's Notes

Title: Ruby Objects, Classes and Variables


1
Ruby Objects, Classes and Variables
CS 480/680 Comparative Languages
2
Ruby Classes
  • Remember, in Ruby variables are created
    automatically the first time they are accessed
  • Thus, there is no variable declaration section in
    a Ruby class, variables are created in the
    initialize method (the equivalent of a C
    constructor)

class Song   def initialize(name, artist, duratio
n)     _at_name      name     _at_artist    artist
    _at_duration  duration   end end
3
Using the Class
aSong  Song.new("Bicylops", "Fleck", 260) aSong.i
nspect "ltSong0x401b299c _at_artist\"Fleck\", _at_n
ame\"Bicylops\", _at_duration260gt"
aSong.to_s "ltSong0x401b2a14gt"
  • How can we call to_s and inspect, when we have
    not defined them for this class?
  • Answer All classes are subclasses of class
    Object
  • to_s and inspect are inherited from Object

4
Overriding the Superclass
class Song   def to_s     "Song _at_name--_at_ar
tist (_at_duration)   end End aSong  Song.new
("Bicylops", "Fleck", 260) aSong.to_s "Song Bic
ylops--Fleck (260)"
  • Classes can be reopened any time
  • Which means that you can override or extend
    built-in classes just by opening them
  • Notice the missing return() in to_s

5
Inheritance
class KaraokeSong lt Song def initialize(name,
artist, duration, lyrics) super(name, artist,
duration) _at_lyrics lyrics end end
  • lt Song indicates that KaraokeSong is a
    subclass of Song. All methods of Song are
    included in KaraokeSong
  • Data members are not explicitly included, but the
    are created by the call to super in initialize

6
Calling the Superclass
class KaraokeSong lt Song Format ourselves
as a string by appending our lyrics to our
parent's to_s value. def to_s super
" _at_lyrics" end end aSong
KaraokeSong.new("My Way", "Sinatra", 225, "And
now...") aSong.to_s "Song My Way--Sinatra
(225) And now..."
  • Calling super with no arguments calls the
    same-named method in the superclass with the same
    arguments

7
Accessing Data Members
class Song attr_reader name, artist,
duration end Is the same as this class Song
def name _at_name end def artist
_at_artist end def duration
_at_duration end end
8
Writing Data Members
class Song attr_writer duration end Is the
same as this class Song def
duration(newDuration) Methods ending
_at_duration newDuration in are end
special end aSong Song.new("Bicylops",
"Fleck", 260) aSong.duration 260
aSong.duration 257 aSong.duration 257
9
Class state is protected
  • In Ruby, you can only access data members
    (state) of a class through class methods

class Myclass def initialize() _at_state1
0 _at_state2 1 end attr_reader(state1
, state2) end myobj Myclass.new puts
myobj.state1, myobj.state2 myobj.state1 7
objectstate.rb13 undefined method state1' for
ltMyclass0x402b0ed0 _at_state21, _at_state10gt
(NoMethodError)
10
Virtual Data Members
  • When using access methods, data can be converted
    before reporting, so data members can be accessed
    in multiple ways

class Song def durationInMinutes
_at_duration/60.0 force floating point end
def durationInMinutes(value) _at_duration
(value60).to_i end end aSong
Song.new("Bicylops", "Fleck", 260)
aSong.durationInMinutes 4.333333333
aSong.durationInMinutes 4.2 aSong.duration
252
11
Class Variables
  • Class variables store data stored among all
    instances of a class
  • There is only one class variable storage location
    for the entire class
  • Must be initialized before use in the class
    definition
  • Class variables start with _at__at_

12
Class Variables
class Song _at__at_plays 0 Play count for ALL
songs def initialize(name, artist, duration)
_at_name name _at_artist artist
_at_duration duration _at_plays 0 Play
count for THIS song end def play _at_plays
1 _at__at_plays 1 "This song _at_plays
plays. Total _at__at_plays plays." end end
13
Class Methods
  • Some methods need to be run without being
    attached to any particular instance
  • Example Test if a file is readable
  • Cant open the file if it is not readable
  • File.readable?(Filename) might be defined to
    allow this test without any particular file
    variable
  • Defined as Classname.methodName

class Example def instMeth
instance method end def Example.classMeth
class method end end
14
Class Constants
  • Recall that constants begin with uppercase
    letters
  • Constants defined outside of any class are
    global, while those defined within a class are
    local

class SongList MaxTime 560 5
minutes def SongList.isTooLong(aSong)
return aSong.duration gt MaxTime end end
15
Variables in Ruby
  • Variables in Ruby hold references to objects!
  • A reference is basically an address with some
    class/type information
  • This can make assignment somewhat tricky!
  • See variables.rb

16
Singletons
  • Suppose you want only one object of a particular
    class, and every time a new instance is created
    it refers to the same object?
  • This is a design pattern called a singleton

class Logger private_class_method new
_at__at_logger nil def Logger.create _at__at_logger
new unless _at__at_logger _at__at_logger
end end Logger.create.id 537762894
Logger.create.id 537762894
Makes the new() method private
Use Logger.create() instead.
17
Alternative constructors
  • New calls initialize() with the same parameters
    passed to itself.
  • You can call new from other methods

class Shape def initialize(numSides,
perimeter) ... end end class Shape def
Shape.triangle(sideLength) Shape.new(3,
sideLength3) end def Shape.square(sideLength)
Shape.new(4, sideLength4) end end
18
Access Control
  • Access control to methods is C-like

class MyClass def method1 default is
'public' ... end protected
subsequent methods will be 'protected'
def method2 will be 'protected'
... end private subsequent
methods will be 'private' def method3
will be 'private' ... end
public subsequent methods will be
'public' def method4 and this will be
'public' ... end end
19
Alternate notation for access control
  • Alternately, you can do it this way

class MyClass def method1 end ... and
so on public method1, method4 protected
method2 private method3 end
This is the notation for a Ruby symbol. Well
discuss symbols in more detail later
20
Method Access
  • Public available to anyone
  • Private only available to other methods of this
    class called on the same object
  • Protected available only to other methods of
    this class for this and other objects

class Account attr_reader balance protected
balance def greaterBalanceThan(other)
return _at_balance gt other.balance end end
balance() is available to any Account object
21
Exercises
  • Create a Ruby class for Students
  • Name, SSN, midterm, final, array of lab scores,
    array of hw scores
  • Constructor, attr_readers and attr_writers
  • Virtual attributes exam_avg, lab_avg (read-only)
  • Class variable student_count
  • Read 5 or 10 student records from a file into an
    array of student objects, then print them
Write a Comment
User Comments (0)
About PowerShow.com