Ruby Summary
- An exception is a special kind of object, an instance of the class Exception or a descendant of that class.
- The raise method is from the Kernel module. By default, raise creates an exception of the RuntimeError class. To raise an exception of a specific class, you can pass in the class name as an argument to raise.
- To do exception handling, we enclose the code that could raise an exception in a begin-end block and use one or more rescue clauses to tell Ruby the types of exceptions we want to handle.
- It is to be noted that the body of a method definition is an implicit begin-end block; the begin is omitted, and the entire body of the method is subject to exception handling, ending with the end of the method.
- If you write a rescue clause with no parameter list, the parameter defaults to StandardError.
- If you need the guarantee that some processing is done at the end of a block of code, regardless of whether an exception was raised then the ensure clause can be used. ensure goes after the last rescue clause and contains a chunk of code that will always be executed as the block terminates. The ensure block will always run.
- By default, the inspect message, which can be sent to any object, formats the object’s ID and instance variables. It returns a string containing a human-readable representation of object. If not overridden, uses the to_s method to generate the string.
- In Ruby, we rely less on the type (or class) of an object and more on its capabilities. Hence, Duck Typing means an object type is defined by what it can do, not by what it is.
- Duck Typing refers to the tendency of Ruby to be less concerned with the class of an object and more concerned with what methods can be called on it and what operations can be performed on it.
- In Ruby, we would use respond_to? or might simply pass an object to a method and know that an exception will be raised if it is used inappropriately.
- Syntactic sugar refer to special rules that let you write your code in a way that doesn't correspond to the normal rules but that is easier to remember how to do and looks better.
- Ruby allows you to define methods that end with an equal sign (=)
- Mutable objects are objects whose state can change. Immutable objects are objects whose state never changes after creation.
- Mutability is a property of an instance, not of an entire class. Any instance can become immutable by calling freeze.
- The freeze method in class Object prevents you from changing an object, effectively turning an object into a constant. After we freeze an object, an attempt to modify it results in TypeError.
- freeze operates on an object reference, not on a variable. This means that any operation resulting in a new object will work.
- A method frozen? tells you whether an object is frozen or not.