Ruby的initialize方法后,能否运行一个额外的方法呢?
- 内容介绍
- 文章标签
- 相关推荐
本文共计386个文字,预计阅读时间需要2分钟。
在 Ruby 中,若想在调用 `initialize` 方法后执行一些代码,可以直接在 `initialize` 方法中添加所需执行的代码。以下是一个简化的示例,展示了如何在类中定义 `initialize` 方法,并在其中执行代码。
rubyclass Base def initialize puts after init endend
class A A.new 在这个例子中,当创建 `A` 类的实例时,会首先调用 `Base` 类的 `initialize` 方法,因此会输出 after init。 这是我想要的一个例子: 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
本文共计386个文字,预计阅读时间需要2分钟。
在 Ruby 中,若想在调用 `initialize` 方法后执行一些代码,可以直接在 `initialize` 方法中添加所需执行的代码。以下是一个简化的示例,展示了如何在类中定义 `initialize` 方法,并在其中执行代码。
rubyclass Base def initialize puts after init endend
class A A.new 在这个例子中,当创建 `A` 类的实例时,会首先调用 `Base` 类的 `initialize` 方法,因此会输出 after init。 这是我想要的一个例子: 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

