Ruby/Class/child class

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
м (1 версия: Импорт выборки материалов по Ruby)
 

Текущая версия на 17:55, 13 сентября 2010

Содержание

Add methods in subclass

#!/usr/bin/env ruby
class Hello
  def howdy
    greeting = "Hello, myValue!"
    puts greeting
  end
end
class Goodbye < Hello
  def solong
    farewell = "Goodbye, myValue."
    puts farewell
  end
end
friendly = Goodbye.new
friendly.howdy
friendly.solong



Add method to child class

class Pet
  attr_accessor :name, :age, :gender, :color
end
class Cat < Pet
end
class Dog < Pet
  def bark
    puts "Woof!"
  end
end



Add more accessors in child class

class Pet
  attr_accessor :name, :age, :gender, :color
end
class Cat < Pet
end
class Dog < Pet
end
class Snake < Pet
  attr_accessor :length
end



Check class attribute of child class

class Pet
  attr_accessor :name, :age, :gender, :color
end
class Cat < Pet
end
class Dog < Pet
  def bark
    puts "Woof!"
  end
end
 
a_dog = Dog.new
puts a_dog.class