DEV Community

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

Collapse
 
edizle585 profile image
Elijah Logan

So lets say your mom makes super smacking pb &j's using her super smacking pb & j technique (all she does is remove the crust). But today mom had to hurry to work so brother B is making breakfast. Your not sure if b can make pb & j's like mom but he assures you that he's used ( super ) to get moms skill passed down to him so he's qualified. Using super B made you some super smacking pb & j's

class Mom-PB-Technique
def corner-cut(bread)
for corner in bread
corner.cut crust
return bread
end

class B-PB-Technique < Mom-PB-Technique
def corner-cut
super
end

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.