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.rb113 chars10 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.rb33 chars2 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.rb43 chars2 lines
gistlibby LogSnag