add a public property to a class in ruby

To add a public property to a class in Ruby, we can define a getter (to read the value of the property) and a setter (to assign a value to the property). Here is an example code snippet:

main.rb
class MyClass
  attr_accessor :my_property # adds both getter and setter method

  def initialize(value)
    @my_property = value
  end
end
140 chars
8 lines

In this example, we define a class MyClass with a public property my_property. We use the attr_accessor method to automatically generate the getter and setter methods for our property.

The initialize method sets the initial value of the property when an instance of the class is created. We can access the property using dot notation:

main.rb
object = MyClass.new("initial value")
object.my_property = "new value" # sets the value of the property
puts object.my_property # outputs "new value"
150 chars
4 lines

gistlibby LogSnag