Ruby/Class/Overriding Methods
Материал из Wiki.crossplatform.ru
Содержание |
Override method from parent
class CD include Comparable @@plays = 0 attr_reader :name, :artist, :duration attr_writer :duration def initialize(name, artist, duration) @name = name @artist = artist @duration = duration @plays = 0 end def to_s "CD: #@name--#@artist (#@duration)" end def name @name end def inspect self.to_s end def <=>(other) self.duration <=> other.duration end end class CD def to_s puts "new to_s" end end d = CD.new("A", "B", 6) d.to_s
override your own methods
class Dog def talk puts "Woof!" end end my_dog = Dog.new my_dog.talk class Dog def talk puts "Howl!" end end my_dog.talk
Overriding Existing Methods
class String def length 20 end end puts "This is a test".length puts "a".length puts "A really long line of text".length
Overriding Methods Demo
# When you define a method in a class, you can redefine that method in a derived class, # and that"s what overriding is all about - redefining a method in a derived class. class Animal def initialize(color) @color = color end def get_color return @color end end class Dog < Animal def initialize(color) super(color) end def get_color return "blue" end end dog = Dog.new("brown") puts "The new dog is " + dog.get_color