According to Reek, creating a class variable is considered a 'code smell'. What is the explanation behind this?
Ruby Class Variables Class variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.
What is a variable? A variable is a name that Ruby associates with a particular object. For example: city = "Toronto" Here Ruby associates the string "Toronto" with the name (variable) city. Think of it as Ruby making two tables.
Variables in Ruby can contain different values and different types of values over time. The term variable comes from the fact that variables, unlike constants, can take different values over time. In the example, there is a variable called i . First it is assigned a value 5, later a different value 7.
In brief, this:
class Shape
@@sides = 0
def self.sides
@@sides
end
end
class Pentagon < Shape
@@sides = 5
end
puts Shape.sides # oops ... prints 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With