I just learned about static variables in php. Is there anything like that in ruby?
For example, if we want to create a Student
class and for each student
object we create, its id number should get incremented automatically.
I thought creating class variable as a static will do.
In Ruby, there are two implementations for the static keyword: Static Variable: A Class can have variables that are common to all instances of the class. Such variables are called static variables. A static variable is implemented in ruby using a class variable.
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.
If a variable is static , the variable is assigned memory once and all objects of the class access the same variable. A static variable can be created by adding the static keyword before the variable during declaration.
There are different types of variables in Ruby: Local variables. Instance variables. Class variables.
Class variables are shared between all instances (which is why they're called class variables), so they will do what you want. They're also inherited which sometimes leads to rather confusing behavior, but I don't think that will be a problem here. Here's an example of a class that uses a class variable to count how many instances of it have been created:
class Foo @@foos = 0 def initialize @@foos += 1 end def self.number_of_foos @@foos end end Foo.new Foo.new Foo.number_of_foos #=> 2
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