16

my solution is like

if (not (defined?(@results).nil?))
  @results += "run"
else
  @results = "run"
end

but I believe that there is something simpler ...

2 Answers 2

27

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.

1
  • 4
    A variation of this would be @results = "#{@results}run"
    – Jakob S
    Jun 1, 2011 at 9:12
12

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.

7
  • is that correct? Using ||= hence only updates the variable @results if the variable is not nil. Otherwise it updates an empty string "". The update/append is done via << .
    – Radek
    Jun 1, 2011 at 5:21
  • @Radek: Let me clarify further: because a _= b for some operator _ becomes a = a _ b, we get (@results = @results || "") << "run".
    – Aaa
    Jun 1, 2011 at 5:35
  • @Radek: Note that this form is more idiomatic to Ruby as it is a generic pattern.
    – Aaa
    Jun 1, 2011 at 7:23
  • 1
    @Radek: This is what people usually use to do this in Ruby.
    – Aaa
    Jun 1, 2011 at 7:28
  • 1
    This is the best solution here. Basically it means, if @results does not exist, make it, and set its value to to "". If it already exists, append "run" to it. If this is used in a loop, it will create the variable in first cycle of loop, than append values to it in every cycle (including first, right after creation). Mar 28, 2013 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.