shortest latest way to write classes in ruby? in ruby

In the latest versions of Ruby (2.5 and above), you can use a shorter syntax to define classes. This syntax is known as "class definition with keyword arguments". Here's an example:

main.rb
class MyClass
  attr_accessor :name, :age

  def initialize(name:, age:)
    @name = name
    @age = age
  end

  def greet
    puts "Hello, #{@name}! You are #{@age} years old."
  end
end
189 chars
13 lines

With this syntax, you can define the attributes of your class using keyword arguments in the initialize method. The attr_accessor macro is used to define getter and setter methods for the attributes.

You can create an instance of this class and call its methods like this:

main.rb
my_object = MyClass.new(name: "John", age: 25)
my_object.greet
63 chars
3 lines

This will output:

main.rb
Hello, John! You are 25 years old.
35 chars
2 lines

This shorter syntax provides a more concise and readable way to define classes in Ruby.

related categories

gistlibby LogSnag