Suppose a ticket has an `available?` method. An `if` can print a success message when the method’s result is truthy and a sold-out message otherwise. Conditional logic changes which code runs according to the value of an expression. section 2.2.4 section 6.0
The basic form is `if condition`, followed by code and a closing `end`. Add `else` for an alternative. Add any number of `elsif` clauses to test further conditions: Ruby runs the first successful branch and skips the rest. A final `else` runs only if every test fails. Branches can contain more code or nested conditionals. section 6.1.1
def print_conditionally
print "Enter an integer: "
n = gets.to_i
if n > 0
puts "Your number is positive."
elsif n < 0
puts "Your number is negative."
else
puts "Your number is zero."
end
end
print_conditionally
Try entering a positive integer, a negative integer, and zero. The same `if`/`elsif`/`else` statement selects a different message for each. section 6.1.1
A condition need not produce the object `true`. Ruby tests the truthiness of its result: only `false` and `nil` fail an `if` test. Strings, numbers, and even `0` pass. This distinction matters when a method has a side effect: `puts` prints its argument but returns `nil`, so `if puts "hello"` prints `hello` without entering the branch. section 2.2.4 section 7.5.1
Choose the form that keeps the decision clear:
- Use `unless` for a negative test, or negate an `if` test with `not` or `!`. Parenthesize a comparison after `!` when you mean to negate the whole comparison; operator precedence can otherwise change the test. section 6.1.1
- Use a trailing modifier for a short guard, as in `puts "Big number!" if x > 100`. A multiline `if` is easier to follow when there are several branches. section 6.1.1
An `if` is also an expression. If no condition succeeds and there is no `else`, its value is `nil`. In irb, distinguish a message printed by a branch from the value irb reports for the entire expression: a branch calling `puts` also yields `nil` because `puts` returns `nil`. section 2.2.4 section 6.1.1
if false
x = 1
end
p x #1
p y #2
The condition is false, so `x = 1` never runs. Ruby nevertheless recognizes `x` as a local variable while parsing; inspecting it yields `nil`, while inspecting the undeclared `y` raises an error. section 6.1.2
Assigning a match while testing it
`if m = /la/.match(name)` both assigns the match result and tests it. The successful branch can use `m.pre_match` and `m.post_match`; the `else` branch handles no match. Be careful not to confuse assignment (`=`) with comparison (`==`) in a condition. section 6.1.2 section 1.1.2




















