I know PHP & Javascript, but I'm just starting to learn Ruby.
This is currently working :
class Animal
attr_accessor :name, :mammal
def initialize(name)
@name = name
end
end
class Fish < Animal
def initialize(name)
super(name)
@mammal = false
end
end
class Cow < Animal
def initialize(name)
super(name)
@mammal = true
end
end
animals = [
Fish.new('Moppy'),
Cow.new('Marguerite'),
]
animals.each do |animal|
puts "Is #{animal.name} a mammal ? #{animal.mammal}"
end
See the @mammal var in the sub classes ?
They are 'static' variables which do not depend of the instance, but of the class itself (a cow will always be a mammal, while a fish won't)
I was wondering if I was declaring the @mammal var at the right place. Instinctively, I would rather have done this
class Cow < Animal
@mammal = true
def initialize(name)
super(name)
end
end
but then it does not work... Could someone tell me if how you should handle this with Ruby ?
Thanks !