Learning Ruby - 9 - PowerPoint PPT Presentation

About This Presentation
Title:

Learning Ruby - 9

Description:

fred.set_name( 'Fred Reginald Jones' ) fred.to_s. Class Set Methods. class Person. def name=( name ) ... tom = Person.new( 'Thomas', '26/05/1945', :Irish ) ... – PowerPoint PPT presentation

Number of Views:25
Avg rating:3.0/5.0
Slides: 9
Provided by: glasnost
Category:

less

Transcript and Presenter's Notes

Title: Learning Ruby - 9


1
Learning Ruby - 9
  • Classes

2
Creating Classes Manually
  • class Person
  • def initialize( name, dob, nationality )
  • _at_name name
  • _at_dob dob
  • _at_nationality nationality
  • end of initialize.
  • end of Person.
  • fred Person.new( 'Fred Jones', '24/05/1950',
    Irish )
  • fred
  • fred.methods.sort
  • fred.instance_variables

3
Classes to Strings - Dynamically!
  • fred.to_s
  • class Person
  • def to_s
  • "_at_name born on _at_dob (_at_nationality)"
  • end of to_s.
  • end of Person.
  • fred.to_s

4
Class Get Methods
  • class Person
  • def name
  • _at_name
  • end of name.
  • def dob
  • _at_dob
  • end of dob.
  • def nationality
  • _at_nationality
  • end of nationality.
  • end of Person.
  • fred.name
  • fred.to_s
  • fred.dob

5
Class Set Methods
  • class Person
  • def set_name( name )
  • _at_name name
  • end of set_name.
  • def set_dob( dob )
  • _at_dob dob
  • end of set_dob.
  • def set_nationality( nationality )
  • _at_nationality nationality
  • end of set_nationality.
  • end of Person.
  • fred.name
  • fred.set_name( "Fred Reginald Jones" )
  • fred.to_s

6
Working Less
  • class Person
  • def name( name )
  • _at_name name
  • end of name.
  • def dob( dob )
  • _at_dob dob
  • end of dob.
  • def nationality( nationality )
  • _at_nationality nationality
  • end of nationality.
  • end of Person.

7
Working Even More Less
  • class Person
  • attr_reader name, dob, nationality
  • attr_writer name, dob, nationality
  • def initialize( name, dob, nationality )
  • _at_name name
  • _at_dob dob
  • _at_nationality nationality
  • end of initialize.
  • def to_s
  • "_at_name born on _at_dob (_at_nationality)"
  • end of to_s.
  • end of Person.
  • tom Person.new( "Thomas", "26/05/1945",
    Irish )
  • dick Person.new( "Richard", "15/02/1980",
    English )
  • harry Person.new( "Harold", "02/11/1975",
    American )

8
More ... Ruby So Far
  • Creating classes in Ruby is almost too easy
  • The attr_reader and attr_writer shortcuts are
    especially handy
  • Of course, as Ruby supports OO, classes can
    inherit from other classes (and from more than
    one when you use mixins)
  • Public, Protected and Private access controls are
    also available
  • Chapter 3 of The PickAxe has all the details
Write a Comment
User Comments (0)
About PowerShow.com