开发者

Passing data with inheritance?

I have several classes that inherit from a single class. Each child class creates some data structures then the parent class performs operations on that data.

Question: How do I get the parent class to use that data regardless of whether the object is instantiated or not.

class A
  def self.static_test
    puts @myvar + "_static"
  end
  def instantiated_test
    puts @myvar + "_instantiated"
  end
end
class B<A
  @myvar = "this works B"
end
class C<A
  @myvar = "this works C"
end

B.static_test
B.new.instantiated_test
C.static_test
C.new.instantiated_test
B.static_test
B.new.instantiated_test

I would need the above code to print:

this works B_static
this works B_instantiated
this works C_static
this works C_instantiated
this works B_static
this works B_instantiated

I am using Ruby 1.8.7.

Edit: It looks like my original question was a bit confusing. I need both static and instantiated methods to use the s开发者_Go百科ame data. The methods won't be doing the same thing though. I updated the sample code to reflect this.


def instantiated_test
  self.class.static_test
end

BTW, if you are sure that inherited classes will have a certain structure, extract it to parent class. If you are not sure, don't use it at all from parent class. Parent's implementation should not depend on child's implementation.


class A
  class << self
    attr_reader :myvar
  end
  # Alternatively:
  # def self.myvar; @myvar; end

  def self.static_test
    puts myvar
  end
  def instantiated_test
    puts self.class.myvar
  end
end
class B<A
  @myvar = "this works B"
end
class C<A
  @myvar = "this works C"
end

B.static_test
#=> this works B
B.new.instantiated_test
#=> this works B
C.static_test
#=>this works C
C.new.instantiated_test
#=>this works C
B.static_test
#=> this works B
B.new.instantiated_test
#=> this works B


class A
  def self.static_test
    puts @myvar
  end
  def instantiated_test
    puts @myvar
  end
end
class B<A
  @myvar = "this works B"
  @@myvar = @myvar
  def initialize
    @myvar = @@myvar
  end
end
class C<A
  @myvar = "this works C"
  @@myvar = @myvar
  def initialize
    @myvar = @@myvar
  end
end

But this is ugly and requires duplication.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜