|
The code on the previous page allows you to take a shortcut in the coding process and use less steps when wanting to quickly use writable attributes.The reason why this is possible is because this code:
def size=(size)
@size = size
end
equals to this: attr_writer :size
How to create readable and writable attributes
Very easily.You can use both attr_reader and attr_writer OR simply use attr_accessor like this:
class Font
attr_accessor :size
def initialize(size)
@size = size
end
end
[edit] Ruby Class Inheritance
The simplest way of explaining the need for class inheritance is when you need to reuse a class inside another class.What do you do, copy all the code again or just reference the other class ?
class Font
def initialize(size)
@size = size
end
def showsize
return @size
end
end
class Family < Font
def initialize(size, family)
super(size)
@family = family
end
def showfamily
return @family
end
end
font = Family.new(“small”, “Geneva”)
puts “The font belongs to the font family “ + font.showfamily
puts “The font has the size and family,respectively “ + font.showfamily + “,“ + font.showsize
|