When Good isn't Good Enough (14/20)


#1

https://www.codecademy.com/courses/learn-ruby/lessons/object-oriented-programming-i/exercises/when-good-isnt-good-enough?action=lesson_resume

I’m confused about a couple things.

  1. If you “realize that you’ve overwritten a method or attribute defined in that class’ base class” as the lesson says, wouldn’t you simply delete the method or attribute in the derived class instead of using the keyword super ?

  2. How come when the following code is run . . .

class Creature
  def initialize(name)
    @name = name
  end
  
  def fight
    return "Punch to the chops!"
  end
end

class Dragon < Creature
  def fight
    puts "instead of breathing fire..."
    super
  end
end

. . . it puts . . .

instead of breathing fire...
Punch to the chops!

. . . to the console when the fight method has not been called AND the superclass’ fight method does not contain a puts statement?


#2

2) That code by itself doesn’t do anything, presumably the submission test invoked your method. And yeah, calling your method will only output:

instead of breathing fire...

1) You may want to both override it in your own class while still having access to the parent one


#3
class Creature
  def initialize(name)
    @name = name
  end
  
  def fight
    return "Punch to the chops!"
  end
end

class Dragon < Creature
  def fight
    puts "instead of breathing fire..."
    super
  end
end
draco = Dragon.new("draco")
puts draco.fight

That will output what you expect.

You wouldn’t delete a parent method just because one child uses it a bit differently


#4

Thanks for the reply.

  1. I thought that was the idea being demonstrated with the code, but the narrative didn’t really say that, so I thought I was missing something. The narrative implied that you simply wanted to restore an attribute or method that you accidentally overwrote, not augment a superclass’ method.

  2. I guess something behind the scenes must have invoked it, though that’s very confusing to the student, who has up to this point needed to write the code up front and is thus not expecting console output. But, this still doesn’t explain why it’s putting "Punch to the chops!" to the console (see my screenshot I added to the original post).


#5

Well… the submission test straight up prints it.

dwemthy = Dragon.new("Dwemthy")
answer = dwemthy.fight
puts answer

Which, as you say, is entirely unhelpful to what it’s supposed to be doing, which is communicating through those banners


#6

Fitting username you have there for this question :smile:

See my reply to ionatan which explains the source of my confusion a bit better perhaps.


#7

Thanks for checking on that. I’ll submit a report on this lesson with a link to this discussion so they can hopefully improve this section.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.