gpt4 book ai didi

ruby - 在 ruby​​ 的字符串中使用方法返回

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

我不知道如何将方法的返回值放入字符串中。我以为它看起来像这样,

def cat
puts "Purrrrr..."
end

puts "The cat says #{cat}."

但这行不通。我也试过了

puts "The cat says %s." % cat

puts "The cat says #{return.cat}."

还有

puts "The cat says #{send.cat}."  

我一直在尝试和查找东西。

最佳答案

正在运行:

def cat
"Purrrrr..."
end

puts "The cat says #{cat}."
# >> The cat says Purrrrr....

为什么下面的没有给出上面的输出:

def cat
puts "Purrrrr..."
end

puts "The cat says #{cat}."
# >> Purrrrr...
# >> The cat says .

这是因为您在 #cat 方法中使用了 puts "Purrrrr..."。现在,字符串内插方法 #cat 被调用,puts 打印字符串 "Purrrrr..." 并返回 。所以 puts "The cat says #{cat}." 变成了 puts "The cat says #{nil}."。结果输出为:

The cat says .
^

"#{nil}" 的计算结果为空字符串 ("")。所以输出不是你所期望的。

(arup~>~)$ irb
2.0.0-p0 :001 > nil.to_s
=> ""
2.0.0-p0 :002 > "foo #{nil}"
=> "foo "
2.0.0-p0 :003 >

puts "The cat says #{return.cat}."puts "The cat says #{send.cat}." 是无效的 ruby​​ 代码,它们会抛出错误。所以不要尝试这个!

希望对您有所帮助!

关于ruby - 在 ruby​​ 的字符串中使用方法返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21473191/

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