0
0
Rubyprogramming~5 mins

Attr_reader, attr_writer, attr_accessor in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Attr_reader, attr_writer, attr_accessor
O(1)
Understanding Time Complexity

Let's see how using attr_reader, attr_writer, and attr_accessor affects the speed of our Ruby code.

We want to know how the time to access or change object properties grows as we use these shortcuts.

Scenario Under Consideration

Analyze the time complexity of the following Ruby class using these attribute helpers.


class Person
  attr_accessor :name
  attr_reader :age
  attr_writer :email

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

person = Person.new("Alice", 30, "alice@example.com")
person.name = "Bob"
puts person.age
person.email = "bob@example.com"
    

This code defines a class with automatic getter and setter methods for its properties.

Identify Repeating Operations

Look for operations that happen multiple times or grow with input.

  • Primary operation: Accessing or setting instance variables via generated methods.
  • How many times: Each access or set is a single direct operation, no loops or recursion.
How Execution Grows With Input

Each time you get or set a property, it takes the same small amount of time, no matter how many properties or objects you have.

Input Size (n)Approx. Operations
1010 simple property accesses or sets
100100 simple property accesses or sets
10001000 simple property accesses or sets

Pattern observation: The time grows directly with how many times you access or set properties, but each is quick and does not depend on other factors.

Final Time Complexity

Time Complexity: O(1)

This means each property access or change takes the same small amount of time, no matter how many objects or properties exist.

Common Mistake

[X] Wrong: "Using attr_accessor makes property access slower because it adds extra code."

[OK] Correct: These helpers just create simple methods that run very fast, so they do not slow down your program noticeably.

Interview Connect

Understanding how these shortcuts work and their speed helps you write clean and efficient Ruby code, a skill useful in many coding situations.

Self-Check

"What if we replaced attr_accessor with manual getter and setter methods? How would the time complexity change?"