[Ruby] Assign variables in conditional expressions in if statements.

This is a personal memo.

About what if (x = test) is doing. In ruby, assignment can be used in conditional expressions of variables.

Illustration

if x = test
  p x
end

=> nil

With if x = test, the value of the variable test is assigned to the variable x.

If the variable test from which it is assigned is false, the result will be false.

P x "P" is the output. Meaning to output the variable x.


If the variable test has a value, the result of the if statement is true.
test = "test"

if x = test
  p x
end

=> "test"

Recommended Posts

[Ruby] Assign variables in conditional expressions in if statements.
Ruby Learning # 17 If Statements
Ruby Learning # 18 If Statements (Con't)
Use ruby variables in javascript.
[Ruby] conditional branch if statement
Things to note in conditional expressions
[Ruby] if statement concept of conditional expression
[Ruby] Behavior of evaluation of conditional expression in while
Ruby conditional branch. if, conditional operator (ternary operator), unless, case
[Ruby] What if you put each statement in each statement? ??
About regular expressions used in ruby sub method
[Ruby] postfix if
Class in Ruby
Variables / scope (ruby)
Heavy in Ruby! ??
About Ruby variables
Ruby if, case
[Ruby] How to use standard output in conditional branching
Things to keep in mind when using if statements