almost 4 years ago
Super主要是呼叫parent method的內容
  • 不帶括號的 super 會呼叫parent method 的內容
  • 帶括號的 super() 則是呼叫parent method 的內容,並且帶入括號內的參數
接下來看幾個例子
不帶括號的super
class Parent 
  def my_method
    puts "Parent is awesome"
  end
end
 
class Kid < Parent
  def my_method
    puts "Kid is awesome"
    super
  end
end

當呼叫 b 的method時,super會再次呼叫 a method的內容

kid = Kid.new
kid.my_method
 
#Output

"Kid is awesome"
"Parent is awesome"
帶括號的super()
class Parent 
  def my_method(family = "Father")
    puts "#{family} is awesome"
  end
end
 
class Kid < Parent
  def my_method(string = "Mother")
    
    puts "Kid is awesome"
    super(string)
  end
end

當呼叫 b 的method時,super會再次呼叫 a method的內容,並且帶入 b 的參數

kid = Kid.new
kid.my_method
 
#Output

"Kid is awesome"
"Mother is awesome"
← Git Commands Include vs. Extend →
 
comments powered by Disqus