Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

ruby - 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 that there is something simpler ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...