Sobes.tech
Junior

What is an argument for a class?

sobes.tech AI

Answer from AI

An argument for a class in Ruby is a value passed to its initialize method. This method is called when creating a new instance of the class using Class.new or syntactic sugar like ClassName.new(...). Arguments allow configuring the created object by setting its initial state.

class Person
  attr_reader :name, :age

  # The initialize method takes arguments
  def initialize(name, age)
    # and uses them to initialize the instance
    @name = name
    @age = age
  end
end

# When creating an instance, arguments are passed
person1 = Person.new("Alice", 30)
person2 = Person.new("Bob", 25)

puts person1.name # Outputs "Alice"
puts person2.age # Outputs 25

Arguments can be mandatory, optional (with default values), keyword arguments, or variable length (splat operator *).

class Example
  # Mandatory argument, optional with default, keyword argument, variable number of arguments
  def initialize(required_arg, optional_arg = "default", keyword_arg: "keyword", *splat_args)
    puts "Required: #{required_arg}"
    puts "Optional: #{optional_arg}"
    puts "Keyword: #{keyword_arg}"
    puts "Splat: #{splat_args.inspect}" # inspect displays the array
  end
end

# Usage example with different argument types
Example.new(1)
# Output:
# Required: 1
# Optional: default
# Keyword: keyword
# Splat: []


Example.new(1, 2, keyword_arg: "custom value", 3, 4)
# Output:
# Required: 1
# Optional: 2
# Keyword: custom value
# Splat: [3, 4]