Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to append a string to a variable that either exists or not?

Tags:

ruby

my solution is like

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

but I believe that there is something simpler ...

like image 1000
Radek Avatar asked Jun 01 '11 04:06

Radek


People also ask

How do you add a string to a variable?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.

How do you append to a variable?

Create an Append Variable activity with UISelect the Append Variable activity on the canvas if it is not already selected, and its Variables tab, to edit its details. Select the variable for the Name property. Enter an expression for the value, which will be appended to the array in the variable.

How do you append a variable in ruby?

You can use the + operator to append a string to another. In this case, a + b + c , creates a new string.

What does append to string variable mean?

The “append to string variable” will always add to the end of the variable's string value, including spaces or any other character.


2 Answers

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.

like image 166
DigitalRoss Avatar answered Sep 17 '22 13:09

DigitalRoss


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.

like image 20
Aaa Avatar answered Sep 17 '22 13:09

Aaa