create a class in ruby

To create a class in Ruby, use the class keyword followed by the class name. Inside the class definition, you can define methods and instance variables that will be available to objects created from the class. Here's an example:

main.rb
class MyClass
  def initialize(name)
    @name = name
  end
  
  def greet
    puts "Hello, #{@name}!"
  end
end
113 chars
10 lines

In this example, MyClass is the name of the class. The initialize method is a special method that gets called when an object is created from the class. In this case, it takes a name argument and sets an instance variable @name to the value of the argument.

The greet method prints out a greeting using the value of the @name instance variable.

To create an object from the class, you can use the new method:

main.rb
my_object = MyClass.new("Alice")
33 chars
2 lines

This creates a new object from the MyClass class, passing in the argument "Alice" to the initialize method. You can then call the greet method on the object like this:

main.rb
my_object.greet #=> prints "Hello, Alice!"
43 chars
2 lines

gistlibby LogSnag