call a static property on an instance of a class in ruby

To call a static property on an instance of a class in Ruby, you would use the class name followed by the property name. Here is an example:

main.rb
class MyClass
  @@my_static_property = "Hello, world!"

  def print_static_property
    puts self.class.my_static_property
    # or you could use MyClass.my_static_property
  end

  def self.my_static_property
    @@my_static_property
  end
end

my_instance = MyClass.new
my_instance.print_static_property
306 chars
16 lines

In this example, @@my_static_property is a static property defined on the MyClass class. To access this property from an instance of the class, print_static_property uses the class name self.class and the syntax class_name.static_property_name to access the value of my_static_property. Output of the above program will be:

main.rb
Hello, world!
14 chars
2 lines

gistlibby LogSnag