Ruby Module and Class (Mix-in vs Inheritance)
That would be tricky to decide when to use module or inheritance in Ruby or any other language (behavior vs is-a relationship).
- Use the module if the class has many behaviors and use the module when you tend not to have instantiated objects.
- Use inheritance if the class belongs to only one superclass and the superclass might need to be instantiated. Class inheritance is mostly applied to real-world objects that might have general strategies and sub-strategies.
Special note: It sounds more restrictive to design with class with inheritance. It is a linguistic challenge. A subclass has to be a type of superclass. Unlikely, the module provides more flexibility. It groups the behavior of a similar object. No discrimination.
What happens if the class and module have the same method? Which one the object will use?
The result from the above code:
foo from its class.
bar from module.
To sum up, the method lookup chain is in the following order:
- Its class
- Modules mixed into its class, in reverse order of inclusion
- The class’s superclass
- Modules mixed into the superclass, in reverse order of inclusion
- Likewise, up to Object (and its mix-in Kernel) and Basicobject
How about defining the same method in the same class?
It will take the latest one. The bottom one.
array1 << value is different from array1 + [value]
array1 << valueis a statement; equivalent to
array1 = array1 + [value]
array1 + [value]is an expression
arr1 = [1,2,3]
arr2 = arr1 << 4 # It is same as arr2 = arr1 = arr1 + 
puts arr1.inspect # => [1,2,3,4]
puts arr2.inspect # => [1,2,3,4]arr3 = [1,2,3]
arr4 = arr3 + 
puts arr3.inspect # => [1,2,3]
puts arr4.inspect # => [1,2,3,4]
Ruby Bitwise and Logical Operation
Because Ruby is dynamic language, it is tricky with bitwise and logical operation unlike static languages such as Java. Here are the common notes about them in Ruby:
- ||, && are logical operation
|| return first value if both value true
&& return second value if both value true
3 && 4 => 4false && 4 => false4 && false => false3 || 4 => 3false || 4 => 43 || false => 3# but be cautious between false and nil, it is reverse between || and &&false && nil => false
nil && false => nilfalse || nil => nil
nil || false => false
- |, & is bitwise operation
3 & 4 => 0
false & 4 => false
3 | 4 => 7
false | 4 => true
Chic way to swap value between variables
a, b = b, c