Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 类方法'self.'类内方法块'class<&书信电报;红宝石中的self_Ruby_Ruby 2.5 - Fatal编程技术网

Ruby 类方法'self.'类内方法块'class<&书信电报;红宝石中的self

Ruby 类方法'self.'类内方法块'class<&书信电报;红宝石中的self,ruby,ruby-2.5,Ruby,Ruby 2.5,context:我目前正在与gem合作,试图处理公共方法的所有案例 我已经编写了下一个代码,希望它在运行时失败。但事实并非如此 class-Foo 类Ruby中的每个对象都有自己的。这是定义实例的所有方法的地方 考虑下面的例子 class C; end c1, c2 = C.new, C.new c1.extend(Module.new { def m1; 42; end }) c1.m1 #⇒ 42 c2.m1 #⇒ NoMethodError: undefined method `m1'

context:我目前正在与gem合作,试图处理公共方法的所有案例

我已经编写了下一个代码,希望它在运行时失败。但事实并非如此

class-Foo

类Ruby中的每个对象都有自己的。这是定义实例的所有方法的地方

考虑下面的例子

class C; end
c1, c2 = C.new, C.new
c1.extend(Module.new { def m1; 42; end })

c1.m1
#⇒ 42
c2.m1
#⇒ NoMethodError: undefined method `m1' for #<C:0x000055cb062e6888>

c1.singleton_class.instance_methods.grep /m1/
#⇒ [:m1]
c2.singleton_class.instance_methods.grep /m1/
#⇒ []
C类;结束
c1,c2=C.新,C.新
扩展(Module.new{defm1;42;end})
c1.m1
#⇒ 42
c2.m1
#⇒ NoMethodError:未定义的方法“m1”#
c1.singleton_class.instance_methods.grep/m1/
#⇒ [:m1]
c2.singleton_class.instance_methods.grep/m1/
#⇒ []
需要Singleton类来扩展对象等

在Ruby中,一切都是对象。类实际上也是对象。这就是为什么每个类都有自己的单例类。每个单例类都有自己的单例类

c1.singleton_class.singleton_class.singleton_class.singleton_class
#⇒ #<Class:#<Class:#<Class:#<Class:#<C:0x000055cb0459c700>>>>>
c1.singleton_class.singleton_class.singleton_class.singleton_class.singleton_class
#⇒ #
foo
上定义的方法存储在
foo
的单例类中。在
foo
的单例类中定义的方法存储在
foo
的单例类的单例类中。等等


这不是很实用,但它仍然是可能的,因为Ruby将所有东西都视为
对象

Foo.singleton\u class.met
。你打开了一个单例类,并在它的单例类上定义了一个方法。我想要一些关于否决票的解释。。。和@AlekseiMatiushkin我一直在寻找关于
singleton_类
的解释,但每个案例都引用了
singleton_类
在类实例上的用法。因此我真的不明白这里的用法:/Downvote不是我的;我会把答案贴出来,解释细节。为了保持热情不变,我投了赞成票。