gpt4 book ai didi

ruby - ruby 模块中 'self' 的结果

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:42 25 4
gpt4 key购买 nike

module Cnblog2jekyll
class << self
attr_accessor :username


[:archive_links, :article_links].each do |method_name|
define_method method_name do
instance_value = instance_variable_get(("@" + method_name.to_s).to_sym)
instance_value ? instance_value : send("get_" + method_name.to_s)
# @archive_links ? @archive_links : get_archive_links
end
end

binding.pry

def test
binding.pry
end


end
end

请忽略大部分代码的含义,注意'binding.pry'的位置。

问题来了:我在 pry 控制台的 'binding.pry' 处输入 'self',结果如下:

From: /home/yanying/cnblog2jekyll/lib/cnblog2jekyll.rb @ line 20 :

15: instance_value = instance_variable_get(("@" + method_name.to_s).to_sym)
16: instance_value ? instance_value : send("get_" + method_name.to_s)
17: # @archive_links ? @archive_links : get_archive_links
18: end
19: end
=> 20: binding.pry
21:
22: def test
23: binding.pry
24: end
25:

[1] pry(#<Class>)> self
=> #<Class:Cnblog2jekyll>
[2] pry(#<Class>)> self.class
=> Class
[3] pry(#<Class>)> self.ancestors
=> [#<Class:Cnblog2jekyll>, Module, Object, PP::ObjectMixin, Kernel, BasicObject]
[4] pry(#<Class>)>
=> true
[2] pry(main)> Cnblog2jekyll.test

From: /home/yanying/cnblog2jekyll/lib/cnblog2jekyll.rb @ line 23 Cnblog2jekyll.test:

22: def test
=> 23: binding.pry
24: end

[1] pry(Cnblog2jekyll)> self
=> Cnblog2jekyll
[2] pry(Cnblog2jekyll)> self.class
=> Module
[3] pry(Cnblog2jekyll)> self.ancestors
=> [Cnblog2jekyll]
[4] pry(Cnblog2jekyll)>

所以,我的问题是:为什么“self”的第一个结果是“Class”?但是第二个是“模块”?这里有什么魔力?

最佳答案

由于您使用的是 class << self ,你打开一个self单例类,里面的方法重新定义了当前的方法self ,在你的例子中是 module Cnblog2jekyll

如果你有:

class Cnblog2jekyll
def foo

end

class << self
def bar

end
end
end

你调用Cnblog2jekyll.new.bar你会得到一个 undefined_method ,因为 bar 被指定为类方法,而不是对象方法。在您的情况下,您的方法是 module方法,因为 class << self在模块 block 内。

查看 this question关于 class << self成语也this article关于它。

关于ruby - ruby 模块中 'self' 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29632798/

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