Ref. WGR Chapter 3, Organizing objects with classes
class Cookie
def sweeten(more_chips = 10)
@chips ||= 0 # lazy initialization
@chips += more_chips
end
def yummy?
@chips and @chips >= 20
end
end
To create an object, call the new method on its class
cookie = Cookie.new
To call a method an object, use the dot operator
cookie.sweeten(50)
cookie.yummy? #=> true
class Cookie
def initialize
@chips = 0
end
end
cookie = Cookie.new # *not* Cookie.initialize!
Active initialization (inside the constructor) leads to simpler code elsewhere in the object, since other methods can assume the instance variables are ready to roll.
class Cookie
def initialize
@chips = 0 # active initialization
end
def sweeten(more_chips = 10)
@chips += more_chips
end
def yummy?
@chips >= 20
end
end
class Cookie
def sweeten(more_chips = 10)
@chips ||= 0 # lazy initialization
@chips += more_chips
end
def yummy?
@chips and # defensive coding
@chips >= 20
end
end
new
do?So by the time assignment (=
) happens, the object has been constructed and initialized.
So a constructor is your one big chance to initialize everything before anyone else gets a pointer to it.
class Cookie
def bake
@temp = 350
end
end
@
self
is that objectclass Person
def age=(years_old)
@age = years_old
end
def age
@age
end
end
alice = Person.new
alice.age= 17
alice.age #=> 17
alice.@age #=> SyntaxError
alice.age = 17
is the same as
alice.age=(17)
class Person
def age=(years_old)
@age = years_old
end
def bar_mitzvah!
age = 13 # oops
end
end
age = 13
" looks like a local variable assignment, which takes precedenceself.age
"
@age
class Person
def age=(years_old)
@age = years_old
end
def bar_mitzvah!
@age = 13
end
def bat_mitzvah!
self.age = 13
end
end
aka "macros"
class Thing
attr_reader :age # def age; @age; end
attr_writer :age # def age=(x); @age = x; end
attr_accessor :age # both of the above
end
class Person
attr_accessor :age
def initialize
@age = 20
end
end
alice = Person.new
alice.age #=> 20
class Thing
attr_accessor :foo, :bar
end
thing = Thing.new
=> #<Thing:0x007fe008897278>
>> thing.methods
=> [:foo, :foo=, :bar, :bar=,
attr_reader
et al. defined?Object
Class
or Module
; I'm not sure.attr_accessor
is misnamedreader
, but attr_accessor
makes a reader and a writerattribute
class Cookie
def chips
@chips ||= 10
end
end
class Person
def child?
@age < 18
end
end
alice.age = 16
alice.child? #=> true
Note: query methods return a boolean by convention only
class Person
def birthday!
@age = @age + 1
end
end
!
" is pronounced "bang"!
" means: raise exception if failureclass BadStudent
attr_accessor :first_name, :last_name
end
joe = BadStudent.new
joe.first_name = "Joe"
joe.last_name = "Blow"
puts joe.first_name + " " + joe.last_name
class GoodStudent
def initialize first_name, last_name
@first_name, @last_name = first_name, last_name
end
def full_name
"#{@first_name} #{@last_name}"
end
end
jane = GoodStudent.new("Jane", "Brain")
puts jane.full_name
/