Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Ruby%20On%20Rails%20Interview%20Questions%20and%20Answers

Question: What are Class Variables? How to define them?
Answer:

Class variables are created using the @@ prefix to denote the variable as class level. 

It works just like any other variable, however in the case of inheritance it works more like a static variable that is accessed across all variable instances.

Another example can be found here:

class DemoClass 
 @@my_var = nil
  def initialize
    @@my_var = "hello world"
  end
  def my_var
    puts @@my_var
  end
end
class Demo2Class < DemoClass
  def initialize
    @@my_var = "goodbye world"
  end
end
demo1 = DemoClass.new
demo1.my_var
demo2 = Demo2Class.new
demo2.my_var
demo1.my_var
The output would be as shown below:
hello world
goodbye world
goodbye world
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook