gpt4 book ai didi

ruby - 为单例类定义初始化在 Ruby 中有意义吗?

转载 作者:数据小太阳 更新时间:2023-10-29 08:46:37 25 4
gpt4 key购买 nike

我预计我不会在这里尝试做任何实际的事情,只是想了解一些更深层次的 Ruby 概念。

假设我有以下代码

class Bookshelf
@book_qty = 100 # class instance var

class << self
attr_accessor :books_qty
end

def initialize
@book = "This book is in every object as an object instance variable"
end

# so far so good, but what happens with...

def self.initialize # what would be this called on ?
puts " and at what step would this be printed, if ever?"
# I thought it would be printed when the class code is parsed first time,
# but no
end

# or also

class << self
def initialize
puts "same here"
end
end

end

我知道它可能没有意义,或者可能与 Ruby 内部的工作原理过于复杂相关,但是,如果碰巧有人对此感到困惑并且知道答案......请分享它:)

最佳答案

定义initialize 没有意义对于单例类(无论您使用 def self. 还是 class << self )。 initialize仅由 Class#new 调用和...

Bookshelf.singleton_class.new
# TypeError: can't create instance of singleton class

这是不允许的。

如果你想让代码在第一次解析一个类时执行,就把它放在类中

class Bookshelf
puts "class defined!"
end

关于ruby - 为单例类定义初始化在 Ruby 中有意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26169663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com