create a class with a constructor in ruby

To create a class with a constructor in Ruby, you use the initialize method. Here's an example:

main.rb
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end
end
83 chars
7 lines

In this example, we define a class Person with an initialize method that takes two arguments - name and age. Inside the initialize method, we assign these values to instance variables @name and @age.

The instance variables @name and @age are now available throughout the class, and can be accessed by any instance method of the class.

To create an instance of the Person class, we call the new method:

main.rb
person = Person.new("John", 30)
32 chars
2 lines

This creates a new instance of the Person class with name set to "John" and age set to 30.

Now we can access the instance variables of the person object:

main.rb
puts person.name # "John"
puts person.age # 30
47 chars
3 lines

Note that we need to define name and age methods to access the instance variables @name and @age.

gistlibby LogSnag