Bird
0
0

Given this Ruby class:

hard📝 Application Q9 of 15
Ruby - Classes and Objects
Given this Ruby class:
class Employee
  attr_accessor :name
  attr_writer :salary
  def initialize(name, salary)
    @name = name
    @salary = salary
  end
  def display
    "Name: #{@name}, Salary: #{@salary}"
  end
end
emp = Employee.new('Alice', 5000)
emp.name = 'Bob'
emp.salary = 6000
puts emp.display
What will be the output?
AName: Bob, Salary: 5000
BName: Alice, Salary: 6000
CName: Bob, Salary: 6000
DError: undefined method 'salary'
Step-by-Step Solution
Solution:
  1. Step 1: Understand attr_accessor and attr_writer

    attr_accessor :name allows reading and writing name; attr_writer :salary allows writing salary only.
  2. Step 2: Trace changes to instance variables

    emp.name changed to 'Bob', emp.salary changed to 6000, display shows updated values.
  3. Final Answer:

    Name: Bob, Salary: 6000 -> Option C
  4. Quick Check:

    attr_accessor = read/write, attr_writer = write only [OK]
Quick Trick: attr_writer hides getter, attr_accessor shows both [OK]
Common Mistakes:
  • Expecting salary getter to exist
  • Assuming salary remains unchanged
  • Confusing attr_writer with attr_accessor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes