#1 (Almost) Everything is true
- Every value is
- The number zero is
- Use the
nil?method to differentiate between
#2 All objects could be nil
nilobjects into the expected type (eg use
Hash#compactremoves all nil elements.
Hash#digreturns nil if any intermediate step is nil.
#4 Constants are mutable
- Always freeze constants to prevent them form being mutated (eg
TIMEOUT = 5.freeze).
#7 Different behaviours of
- When you override a method from inheritance hierarchy the
superkeyword can be used to call the overriden method.
superwith no arguments and parentheses is equivalent to passing it all of the arguments that were given to the enclosing method.
- If you want to use
superwithout passing the overriden method any arguments, you must use empty parentheses (eg
Struct for structured data
- When dealing with structured data which doesn't quite justify a new lass prefer using
- Assign the return value of
Struct::newto a constant and treat that constant like a class (eg
Reading = Struct.new(:date, :high, :low))
#12 Different flavors of equality
- Never ovveride the
equal?method. It's expected to strictly compare objects and return
trueonly if they're both pointers to the same object in memory (have the same
Hashclass uses the
eql?method to compare objects used as keys during collisions. The default implementation probably doesn't do what you want. You need to implement
<=>, then alias
==and write a sensible
- Use the
==operator to test if two objects represent the same value.
caseexpressions use the
===operator to test each
whenclause. The left operand is the argument given to
whenand the right operand is the argument given to
13 Compare via
<=> and the
- Implement object ordering by defining a
<=>operator and including the
<=>operator should return
nilif the left operand can't be compared with the right.
15 Class instance variables over class variables
- Prefer class instance variables to class variables.
- Classes are objects and so have their own private set of instance variables.
16 Duplicate collections before mutating them
- Method arguments are passed as references, not values (except
- Duplicate collections passed as arguments before mutating them, eg
@collection = collection.dup.
clonemethods only create shallow copies. For most objects,
Marshalcan be used to create deep copies.