Ruby如何用双引号(“”)和String.new初始化一个新字符串有什么不同?出于好奇和实验的目的,我重写了String #initialize:
class String def initialize puts "I <3 bananas" # they're delicious! end end
我想弄清楚的是:为什么这两个例子不同?
# Calling the String class directly,I can declare banana love! irb(main):054:0> String.new I <3 bananas => "" # Using double quotes,this string is not as tasty :( irb(main):055:0> "" => ""
这对研究很烦人,因为每个Google结果似乎都集中在基本的Ruby语法上,而我在Ruby文档中找不到任何东西.
解决方法
根据
Matz:
String objects for literals are already created in the compile time,which is far before you redefine the initialize method. The individual string objects from literals are just copy of the already allocated and initialized objects. The whole purpose of the initialize method is to initialize newly created objects,as the name suggests. I don’t feel any need to call the (redefined) initialize method for string literals,that already initialized at the compile time.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。