Bird
0
0

Identify the error in the following Ruby code that tries to chain methods:

medium📝 Debug Q14 of 15
Ruby - Functional Patterns in Ruby
Identify the error in the following Ruby code that tries to chain methods:
class Person
  def initialize(name)
    @name = name
  end

  def greet
    puts "Hello, #{@name}!"
  end

  def farewell
    puts "Goodbye, #{@name}!"
  end
end

p = Person.new("Sam")
p.greet.farewell
Ainitialize method missing return statement
Bfarewell method is misspelled
CCannot create Person object with new
Dgreet method does not return self, so chaining fails
Step-by-Step Solution
Solution:
  1. Step 1: Check method return values

    greet prints a message but returns nil (default for puts).
  2. Step 2: Understand chaining requirement

    For chaining, greet must return self to allow calling farewell next.
  3. Final Answer:

    greet method does not return self, so chaining fails -> Option D
  4. Quick Check:

    Method chaining needs methods to return self [OK]
Quick Trick: Ensure methods return self to chain calls [OK]
Common Mistakes:
  • Assuming puts returns self
  • Thinking initialize needs explicit return
  • Believing object creation is the problem

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes