Ruby On Rails 面接の質問と回答
Question: How can you call the base class method from inside of its overridden method?Answer:If you are inside the overridden method in the derived class then a simple call to super will call the right method in the base class class Parent
def try_this()
puts "parent"
end
end
class Child < Parent
def try_this()
super()
puts "child"
end
end
ch = Child.new
ch.try_this()
This generates the output parent child Now if you just want to call the base class without calling the derived class then the best way to do that is to simply assign an alias to the parent method like this: class Parent
def knox
puts 'parent'
end
end
class Child < Parent
alias_method :parent_knox, :knox
def knox
puts 'child'
end
end
ch = Child.new
ch.parent_knox
ch.knox
This allows you to call the base class method with the alias parent_knox and the derived class method knox can be called directly. parent child |
復習用に保存
この項目をブックマークに追加したり、難しい内容としてマークしたり、復習セットに入れたりできます。
役に立ちましたか? はい いいえ
ユーザー評価で最も役立つ内容:
- What is Ruby On Rails?
- Why Ruby on Rails?
- Explain how (almost) everything is an object in Ruby.
- What are Gems and which are some of your favorites?
- How would you declare and use a constructor in Ruby?