how to append a string to a variable that either exists or not?
my solution is like
if (not (defined?(@results).nil?))
@results += "run"
else
@results = "run"
end
but I believe th开发者_JAVA技巧at there is something simpler ...
I would probably do it like this:
@results = @results.to_s + "run"
This works because NilClass
defines a #to_s
method that returns a zero-length String, and because instance variables are automatically initialized to nil.
You're right:
(@results ||= "") << "run"
To clarify, a || b
is a ? a : b
, meaning that it tries to use the value a
if a
is "truthy" (not false or nil) but uses b
if a
is "falsey". Using ||=
hence only updates a variable if the variable is nil. Then, <<
appends the string.
精彩评论