在ruby中,initialize方法执行后,紧接着应该调用哪个方法?

更新于
2026-10-09 20:22:52
1阅读来源:SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计353个文字,预计阅读时间需要2分钟。

在ruby中,initialize方法执行后,紧接着应该调用哪个方法?

在Ruby中,如果你想编写在调用`initialize`方法后执行的代码,你可以在类中定义一个名为`after_init`的方法,并在`initialize`方法执行完毕后调用它。以下是一个简化的例子:

rubyclass Base def initialize # 初始化代码 after_init end

在ruby中,initialize方法执行后,紧接着应该调用哪个方法?

def after_init puts after init endend

class A

A.new # 输出: after init

我想编写一些在调用initialize方法后运行的 ruby代码.此代码可以在类或模块中.我怎么写这个?

这是我想要的一个例子:

class Base def after_init puts "after init" end class A < Base # Option 1, use a class end class B < Base def initialize puts "in init" end end module MyMod def after_init puts "after init" end end class C include Module end $> A.new => "after init" $> B.new => "in init" => "after init" $> C.new => "after init"

我绝对不想做的是明确调用super.有没有办法做到这一点?我不在乎它是否使用了很多Ruby的反射能力.谢谢!

class Base def after_init puts "Base#after_init" end def self.inherited(klass) class << klass alias_method :__new, :new def new(*args) e = __new(*args) e.after_init e end end end end module MyMod def after_init puts "MyMod#after_init" end def self.included(klass) class << klass alias_method :__new, :new def new(*args) e = __new(*args) e.after_init e end end end end class A < Base end class B < Base def initialize puts "B#initialize" end end class C include MyMod def initialize puts "C#initialize" end end A.new B.new C.new

本文共计353个文字,预计阅读时间需要2分钟。

在ruby中,initialize方法执行后,紧接着应该调用哪个方法?

在Ruby中,如果你想编写在调用`initialize`方法后执行的代码,你可以在类中定义一个名为`after_init`的方法,并在`initialize`方法执行完毕后调用它。以下是一个简化的例子:

rubyclass Base def initialize # 初始化代码 after_init end

在ruby中,initialize方法执行后,紧接着应该调用哪个方法?

def after_init puts after init endend

class A

A.new # 输出: after init

我想编写一些在调用initialize方法后运行的 ruby代码.此代码可以在类或模块中.我怎么写这个?

这是我想要的一个例子:

class Base def after_init puts "after init" end class A < Base # Option 1, use a class end class B < Base def initialize puts "in init" end end module MyMod def after_init puts "after init" end end class C include Module end $> A.new => "after init" $> B.new => "in init" => "after init" $> C.new => "after init"

我绝对不想做的是明确调用super.有没有办法做到这一点?我不在乎它是否使用了很多Ruby的反射能力.谢谢!

class Base def after_init puts "Base#after_init" end def self.inherited(klass) class << klass alias_method :__new, :new def new(*args) e = __new(*args) e.after_init e end end end end module MyMod def after_init puts "MyMod#after_init" end def self.included(klass) class << klass alias_method :__new, :new def new(*args) e = __new(*args) e.after_init e end end end end class A < Base end class B < Base def initialize puts "B#initialize" end end class C include MyMod def initialize puts "C#initialize" end end A.new B.new C.new