gpt4 book ai didi

ruby - Ruby 如何评估双引号(又名 "")与 String.new?

转载 作者:数据小太阳 更新时间:2023-10-29 06:53:39 24 4
gpt4 key购买 nike

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.

关于ruby - Ruby 如何评估双引号(又名 "")与 String.new?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16139116/

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