如何将字符串附加到存在或不存在的变量? [英] how to append a string to a variable that either exists or not?
本文介绍了如何将字符串附加到存在或不存在的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的解决方案就像
if (not (defined?(@results).nil?))
@results += "run"
else
@results = "run"
end
但我相信有更简单的东西......
but I believe that there is something simpler ...
推荐答案
我可能会这样做:
@results = @results.to_s + "run"
这是有效的,因为 NilClass
定义了一个 #to_s
方法,它返回一个零长度的字符串,并且因为实例变量会自动初始化为 nil.
This works because NilClass
defines a #to_s
method that returns a zero-length String, and because instance variables are automatically initialized to nil.
这篇关于如何将字符串附加到存在或不存在的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文