- Every value is
trueexceptfalseandnil. - The number zero is
truein Ruby. - Use the
nil?method to differentiate betweenfalseandnil.
- Coerce
nilobjects into the expected type (eg useto_iandto_s). Array#compact/Hash#compactremoves all nil elements.Array#dig/Hash#digreturns nil if any intermediate step is nil.
- Always freeze constants to prevent them form being mutated (eg
TIMEOUT = 5.freeze).
- When you override a method from inheritance hierarchy the
superkeyword can be used to call the overriden method. - Using
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 (egsuper()).
- When dealing with structured data which doesn't quite justify a new lass prefer using
StructtoHash. - Assign the return value of
Struct::newto a constant and treat that constant like a class (egReading = Struct.new(:date, :high, :low))
- Never ovveride the
equal?method. It's expected to strictly compare objects and returntrueonly if they're both pointers to the same object in memory (have the sameobject_id). - The
Hashclass uses theeql?method to compare objects used as keys during collisions. The default implementation probably doesn't do what you want. You need to implement<=>, then aliaseql?to==and write a sensiblehashmethod. - Use the
==operator to test if two objects represent the same value. caseexpressions use the===operator to test eachwhenclause. The left operand is the argument given towhenand the right operand is the argument given tocase.
- Implement object ordering by defining a
<=>operator and including theComparablemodule. - The
<=>operator should returnnilif the left operand can't be compared with the right.
- Prefer class instance variables to class variables.
- Classes are objects and so have their own private set of instance variables.
- Method arguments are passed as references, not values (except
Fixnumobjects). - Duplicate collections passed as arguments before mutating them, eg
@collection = collection.dup. - The
dupandclonemethods only create shallow copies. For most objects,Marshalcan be used to create deep copies.
- Use the
Arraymethod to convertniland scalar objects into arrays - Don't pass
Hashto theArraymethod; it will get converted into a set of nested arrays