Boolean and nil
true and false are the two values of the class Boolean, and nil, the absence of a
value, is the one value of NilClass.
Truthiness
Section titled “Truthiness”Only false and nil count as false in a condition. Everything else is true, 0, "" and
[] included.
puts(0 ? "true" : "false") # trueputs("" ? "true" : "false") # trueputs(nil ? "true" : "false") # falseputs(nil || 5) # 5!, && and || work on any values, && and || giving one of their operands; see
Operators. &, | and ^ aren’t defined for Booleans.
Boolean
Section titled “Boolean”b.to_sb.inspect"true" or "false". Returns: String.
b.to_ib.to_f1 for true, 0 for false: for counting what holds. Returns: Number.
invert
Section titled “invert”b.invertThe other Boolean, as !b. Returns: Boolean.
holes = [true, false, true]puts holes.map { |h| h.to_i }.sum # 2puts true.invert # falsenil answers only the methods every value has (Object):
nil.nil? and nil.empty? are true, nil.inspect is "nil" and nil.class is
NilClass. It has no to_s, to_a or to_i.
puts nil prints nil, and so does "#{nil}", where Ruby gives an empty string. Test for it
first, or give a default with ||: "#{label || ""}".
Passing nil for an optional parameter of a built-in leaves the parameter unset, as if it
weren’t given: slice(nil) and segments: nil take their defaults. A method of your own does
the same for a parameter with a default (see Methods), so a
value passed on may be absent.
label = nilputs label.nil? # trueputs "[#{label || "unnamed"}]" # [unnamed]