微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby – 命名Class.new

为什么为Class.new分配名称/常量会以这种方式运行?

c = Class.new #=> <Class:0xnnnnnnn>
puts c  #=> <Class:0xnnnnnnn>

b = c
puts b #=> <Class:0xnnnnnnn>

NewClass = c   #=> NewClass  <shouldn't it be same as above #=> <Class:0xnnnnnnn>
puts c  #=> NewClass  <and Now c has a name although it was not the left operand above>

解决方法

后者等同于使用kernel :: const_set

语义类NewClass相当于

c = Class.new
Kernel::const_set :NewClass,c

并赋值给一个常量,即NewClass = c在语义上等价于

Kernel::const_set :NewClass,c

所以当你写作

c = Class.new
NewClass = c

它在语义上和写作一样

class NewClass

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐