DEV Community

Discussion on: Explain the 'super' keyword in ruby like I'm five

Collapse
 
cathodion profile image
Dustin King • Edited

Doesn't doing B-PB-Technique < Mom-PB-Tecnhnique already give you all of mom's methods?

Collapse
 
zspencer profile image
Zee

Yes, it does. super is most useful when over-riding the behavior from a method provided in the ancestor chain. I would revise the example to the following:

class MomPBTechnique
  def corner_cut(bread)
    for corner in bread
      corner.cut crust
    end
    return bread
  end

class MyPBTechnique < MomPBTechnique
  # I like *one* corner to not be cut!
  def corner_cut
    first_corner = self.bread[0] # Gets the first corner
    self.bread = bread.slice(1, -1) # Sets the bread to only the last 3 corners
    super # Calls the `corner_cut` method defined in `MomPBTechnique`
    return bread.unshift(first_corner) # Places the un-cut first corner back in the bread
  end
end

This more clearly demonstrates how super can be used to re-use-but-still-change behavior in the class hierarchy.