When you inherit from a parent class, sometimes you want the child's method to behave slightly differently but still use the parent method's behavior.
Let's say you have a Greeter, and their job is to say hi to everyone they meet. If they have the person's name, they'll greet them by name.
classGreeterdefgreet(name=nil)ifnameputs"Hi, #{name}, nice to meet you!"elseputs"Hi, nice to meet you!"endendendGreeter.new.greet#=> Hi, nice to meet you!Greeter.new.greet'Jess'#=> Hi, Jess, nice to meet you!
Now suppose we hire a new greeter from the planet Marklar, who has a religious belief that everyone's name is Marklar. When their greet method calls super, it calls the greet method from their parent class, Greeter:
classMarklarGreeter<Greeterdefgreetsuper'Marklar'endendMarklarGreeter.new.greet#=> Hi, Marklar, nice to meet youMarklarGreeter.new.greet'Jess'#=> ArgumentError: wrong number of arguments (given 1, expected 0)
Okay, we still need greet to take a name parameter, so that we can use a MarklarGreeter anywhere we use a Greeter. This is called the Liskov Substitution Principle. I can't find a link that explains that like you're five, but it basically says an instance of a child class should be usable anywhere you can use an instance of the parent class.
classMarklarGreeter<Greeterdefgreet(name=nil)# We accept a name parameter here, but we ignore it# because everyone's name is Marklarsuper'Marklar'endendMarklarGreeter.new.greet#=> Hi, Marklar, nice to meet you!MarklarGreeter.new.greet'Jess'#=> Hi, Marklar, nice to meet you!
When you inherit from a parent class, sometimes you want the child's method to behave slightly differently but still use the parent method's behavior.
Let's say you have a Greeter, and their job is to say hi to everyone they meet. If they have the person's name, they'll greet them by name.
Now suppose we hire a new greeter from the planet Marklar, who has a religious belief that everyone's name is Marklar. When their
greet
method calls super, it calls thegreet
method from their parent class,Greeter
:Okay, we still need
greet
to take aname
parameter, so that we can use a MarklarGreeter anywhere we use a Greeter. This is called the Liskov Substitution Principle. I can't find a link that explains that like you're five, but it basically says an instance of a child class should be usable anywhere you can use an instance of the parent class.More info about Ruby's super here.