开发者

Inherit initialize() method in ruby? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. F开发者_Go百科or help making this question more broadly applicable, visit the help center. Closed 9 years ago.

I still can't figure out how to make a subclass constructor follow its parent...

example:

require 'mechanize'

class Scraper
    attr_accessor :agent

    def initialize 
    # I dont know if using instance variable is the right thing to do
    @agent = Mechanize.new 
    end
end

class ScraperA < Scraper
end

I want to make ScraperA follow its parent constructor behaviour,

that is instantiate a Mechanize object without me retyping Mechanize.new in ScraperA initialize() method. Is this possible ?

Just want to follow DRY principle but ruby makes it hard for me ???

Hope not, maybe it's just my ignorance. Looking forward for simple solution,Tnx.

Edit:

it turns out that I had empty initialize() method in ScraperA, which override the default initialize(). So yeah the example is working, because no empty initialize method there. Sorry for my stupidity. Tnx.


Umm... eh? Yes it does... Check this out:

class A
  def initialize
    @a = "foo"
  end
end

class B < A
  def to_s
    @a
  end
end

puts B.new
# "foo" is printed

This works because initialize is inherited, just like any other method. If you override it by having a new sub-initialize, it stops working. Then you can explicitly use super to call the parent's initialize.


This should work...

class ScraperA < Scraper

  def initialize
    super

    # do other stuff here if necessary
  end

end

...if you want to have other logic for the subclass. As the comments say if the constructor is exactly the same as for the parent class your original code should work just fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜