开发者

call parent constructor in ruby

开发者 https://www.devze.com 2022-12-28 10:22 出处:网络
How can I call parents constructor ? module C attr_accessor :c, :cc def initialization c, cc @c, @cc = c, cc

How can I call parents constructor ?

module C
    attr_accessor :c, :cc
    def initialization c, cc
        @c, @cc = c, cc
    end 
end

class B
    attr_accessor :b, :bb
    def initia开发者_StackOverflowlization b, bb
        @b, @bb = b, bb
    end 
end


class A < B
    include C
    attr_accessor :a, :aa
    def initialization (a, b, c, aa, bb, cc)
        #call B::initialization - ?
        #call C::initialization - ?
        @a, @aa = a, aa
    end
end

Thanks.


Ruby doesn't have constructors, therefore it's obviously not possible to call them, parent or otherwise. Ruby does have methods, however, and in order to call the parent's method with the same name as the currently executing method, you can use the super keyword. [Note: super without arguments is a shortcut for passing the same arguments that were passed into the currently executing method. If you actually want to pass no arguments, you have to do so explicitly: super().]


Use the super method! Ruby does not have multiple inheritance though.

class B

  attr_accessor :b, :bb

  def initialize(b, bb)
    @b, @bb = b, bb
  end

end

module C

end

class A < B
  include C  # <= if C was a class, you'd get: TypeError: wrong argument type Class (expected Module)

  attr_accessor :a, :aa

  def initialize(a,b,aa,bb)
    @a, @aa = a, aa
    super(b, bb)  # <= calls B#initialize
  end

end

a = A.new(1,2,3,4)
puts a.inspect # => #<A:0x42d6d8 @aa=3, @a=1, @b=2, @bb=4>


First, your method should be initialize, not initialization. Then, you can use super to call the parent class method. As for calling C's initializer in A, for clarity, I'd recommend splitting the initialization stuff into a different function, then just calling that function directly. It's easy to implement, and clearer.


This code below will print :

A.proc1 B.proc1 C.proc1

module A
  def proc1
    puts "A.proc1"
    super
  end
end

class B
  def proc1
    puts "B.proc1"
  end
end

class C < B
  include A
  def proc1
    super
    puts "C.proc1"
  end
end

C.new.proc1
0

精彩评论

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