if – else Statements
# statement-1
if item_counts[item_id] == nil
item_counts[item_id] = 1
else
item_counts[item_id] += 1
end
Another way of achieving the same outcome as statement-1 above:
# statement-2
if item_counts[item_id] == nil
item_counts[item_id] = 0
end
item_counts[item_id] += 1
Another way of writing statement-2 above:
# statement-3
item_counts[item_id] = 0 if item_counts[item_id] == nil
item_counts[item_id] += 1
Another way of achieving the same outcome as statement-3 above:
# statement-4
item_counts[item_id] = 0 if !item_counts[item_id]
item_counts[item_id] += 1
Another way of achieving the same outcome as statement-4 above:
# statement-5
item_counts[item_id] = 0 unless item_counts[item_id]
item_counts[item_id] += 1
if – elsif – else Statements
# statement-6
if item_counts[item_id] == 1
count = 1
elsif item_counts[item_id] == 2
count = 2
else
count = 0
end
Note that it is elsif
, not elseif
and not else if
True or False
In Ruby, every argument in a conditional expression is considered true
except false
and nil
pry> "Blue" if true
=> "Blue"
pry> "Blue" if 0
=> "Blue"
pry> "Blue" if false
=> nil
pry> "Blue" if nil
=> nil
pry> "Blue" if !nil
=> "Blue"