Ruby如何评估双引号(又名“”)与String.new?

前端之家收集整理的这篇文章主要介绍了Ruby如何评估双引号(又名“”)与String.new?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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.

原文链接:https://www.f2er.com/ruby/270313.html

猜你在找的Ruby相关文章