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

To call a public static property on an instance of a class in Ruby, you first need to define a public static property on the class itself. This can be done using the class << self syntax:

main.rb
class MyClass
  class << self
    attr_accessor :my_property
  end
end
71 chars
6 lines

This defines a public static property called my_property on the MyClass class. To call this property on an instance of the class, you simply use the class name:

main.rb
instance = MyClass.new
MyClass.my_property = "Hello, world!"
puts instance.class.my_property #=> "Hello, world!"
113 chars
4 lines

In this example, we create an instance of MyClass and set the my_property property to "Hello, world!". We then print the value of my_property for the instance object using instance.class.my_property, which calls the property on the class object itself. The output of this code will be "Hello, world!".

gistlibby LogSnag