Bird
Raised Fist0
Rubyprogramming~20 mins

To_s method for string representation in Ruby - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Ruby To_s Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Ruby code using to_s?

Consider the following Ruby code:

class Item
  def initialize(name, price)
    @name = name
    @price = price
  end

  def to_s
    "Item: #{@name}, Price: $#{@price}"  
  end
end

item = Item.new("Book", 15)
puts item.to_s

What will be printed?

Ruby
class Item
  def initialize(name, price)
    @name = name
    @price = price
  end

  def to_s
    "Item: #{@name}, Price: $#{@price}"  
  end
end

item = Item.new("Book", 15)
puts item.to_s
AItem: Book, Price: $15
B#<Item:0x00007fffe30b8c20>
CBook 15
DItem Book 15
Attempts:
2 left
💡 Hint

Remember, to_s returns a string representation of the object.

❓ Predict Output
intermediate
2:00remaining
What does this to_s method output for a custom class?

Look at this Ruby code:

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def to_s
    "#{@name} is #{@age} years old"
  end
end

p = Person.new("Alice", 30)
puts p

What will be printed?

Ruby
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def to_s
    "#{@name} is #{@age} years old"
  end
end

p = Person.new("Alice", 30)
puts p
APerson: Alice, 30
B#<Person:0x00007fffe30b8c20>
CAlice is 30 years old
DAlice 30
Attempts:
2 left
💡 Hint

When you puts an object, Ruby calls to_s automatically.

🔧 Debug
advanced
2:00remaining
Why does this to_s method cause an error?

Examine this Ruby code:

class Product
  def initialize(name, price)
    @name = name
    @price = price
  end

  def to_s
    "Product: #{@name}, Price: $#{price}"
  end
end

p = Product.new("Pen", 2)
puts p.to_s

What error will this code raise?

Ruby
class Product
  def initialize(name, price)
    @name = name
    @price = price
  end

  def to_s
    "Product: #{@name}, Price: $#{price}"
  end
end

p = Product.new("Pen", 2)
puts p.to_s
ANameError: undefined local variable or method `price' for #<Product:0x00007fffe30b8c20>
BSyntaxError: unexpected end-of-input
CTypeError: no implicit conversion of Integer into String
DNoMethodError: undefined method `to_s' for Product
Attempts:
2 left
💡 Hint

Check variable names inside string interpolation.

🧠 Conceptual
advanced
1:30remaining
What is the purpose of overriding to_s in Ruby classes?

Why do Ruby programmers override the to_s method in their classes?

ATo change the class name of the object
BTo provide a meaningful string representation of the object for printing or logging
CTo prevent the object from being converted to a string
DTo automatically save the object to a file
Attempts:
2 left
💡 Hint

Think about what puts object shows by default.

❓ Predict Output
expert
2:30remaining
What is the output of this Ruby code with nested to_s calls?

Analyze this Ruby code:

class Point
  def initialize(x, y)
    @x = x
    @y = y
  end

  def to_s
    "(#{@x}, #{@y})"
  end
end

class Line
  def initialize(start_point, end_point)
    @start_point = start_point
    @end_point = end_point
  end

  def to_s
    "Line from #{@start_point.to_s} to #{@end_point.to_s}"
  end
end

p1 = Point.new(1, 2)
p2 = Point.new(3, 4)
line = Line.new(p1, p2)
puts line.to_s

What will be printed?

Ruby
class Point
  def initialize(x, y)
    @x = x
    @y = y
  end

  def to_s
    "(#{@x}, #{@y})"
  end
end

class Line
  def initialize(start_point, end_point)
    @start_point = start_point
    @end_point = end_point
  end

  def to_s
    "Line from #{@start_point.to_s} to #{@end_point.to_s}"
  end
end

p1 = Point.new(1, 2)
p2 = Point.new(3, 4)
line = Line.new(p1, p2)
puts line.to_s
ALine from #<Point:0x00007fffe30b8c20> to #<Point:0x00007fffe30b8c10>
BLine from 1, 2 to 3, 4
C(1, 2) to (3, 4)
DLine from (1, 2) to (3, 4)
Attempts:
2 left
💡 Hint

Each to_s returns a string, so nested calls build the full string.

Practice

(1/5)
1. What does the to_s method do in Ruby?
easy
A. Converts an object to its string representation
B. Converts a string to a number
C. Deletes an object from memory
D. Creates a new object

Solution

  1. Step 1: Understand the purpose of to_s

    The to_s method is used to convert any Ruby object into a string format.
  2. Step 2: Compare options with the definition

    Only Converts an object to its string representation correctly describes this conversion to string. Other options describe unrelated actions.
  3. Final Answer:

    Converts an object to its string representation -> Option A
  4. Quick Check:

    to_s means convert to string [OK]
Hint: Remember: to_s means 'to string' conversion [OK]
Common Mistakes:
  • Confusing to_s with to_i (integer conversion)
  • Thinking to_s deletes objects
  • Assuming to_s creates new objects
2. Which of the following is the correct way to define a custom to_s method in a Ruby class?
easy
A. def to_s; "My object"; end
B. def toString; "My object"; end
C. def tostring; "My object"; end
D. def to_s() "My object" end

Solution

  1. Step 1: Recall Ruby method naming conventions

    Ruby method names are case-sensitive and to_s must be exactly that, with underscore and lowercase.
  2. Step 2: Check syntax correctness

    def to_s; "My object"; end uses correct method name and syntax. def to_s() "My object" end misses semicolon or newline before string, causing syntax error. Options B and C use wrong method names.
  3. Final Answer:

    def to_s; "My object"; end -> Option A
  4. Quick Check:

    Method name must be exactly to_s [OK]
Hint: Use exact method name to_s with underscore [OK]
Common Mistakes:
  • Using wrong method names like toString or tostring
  • Omitting semicolons or line breaks causing syntax errors
  • Using parentheses incorrectly in method definition
3. What will be the output of this Ruby code?
class Person
  def initialize(name)
    @name = name
  end
  def to_s
    "Person named #{@name}"
  end
end

p = Person.new("Alice")
puts p.to_s
medium
A. #
B. Error: undefined method to_s
C. Alice
D. Person named Alice

Solution

  1. Step 1: Understand the custom to_s method

    The class Person defines to_s to return "Person named #{@name}", where @name is set to "Alice".
  2. Step 2: Check what puts p.to_s prints

    Calling p.to_s returns "Person named Alice", which is printed by puts.
  3. Final Answer:

    Person named Alice -> Option D
  4. Quick Check:

    Custom to_s returns formatted string [OK]
Hint: Custom to_s returns your string, not default object info [OK]
Common Mistakes:
  • Expecting default object id string instead of custom string
  • Confusing instance variable with method name
  • Thinking to_s is undefined
4. Identify the error in this Ruby class that tries to customize to_s:
class Car
  def initialize(model)
    @model = model
  end
  def to_s
    "Car model: " + model
  end
end

c = Car.new("Tesla")
puts c.to_s
medium
A. Missing return statement in to_s
B. Syntax error in method definition
C. Undefined local variable or method 'model'
D. No error, prints 'Car model: Tesla'

Solution

  1. Step 1: Check variable usage inside to_s

    The method uses model without @, but the instance variable is @model.
  2. Step 2: Understand Ruby variable scope

    Without @, Ruby looks for a local variable or method named model, which does not exist, causing an error.
  3. Final Answer:

    Undefined local variable or method 'model' -> Option C
  4. Quick Check:

    Instance variables need @ prefix inside methods [OK]
Hint: Use @ before instance variables inside methods [OK]
Common Mistakes:
  • Forgetting @ before instance variables
  • Assuming local variables exist without definition
  • Thinking return statement is mandatory
5. You want to create a Ruby class Book that stores a title and author, and when printed, shows "Title: [title], Author: [author]". Which to_s method correctly achieves this?
hard
A. def to_s "#{title}, #{author}" end
B. def to_s "Title: #{@title}, Author: #{@author}" end
C. def to_s "Title: title, Author: author" end
D. def to_s puts "Title: #{@title}, Author: #{@author}" end

Solution

  1. Step 1: Use instance variables with interpolation

    To show the actual title and author values, use #{@title} and #{@author} inside the string.
  2. Step 2: Avoid printing inside to_s

    to_s should return a string, not print it. def to_s puts "Title: #{@title}, Author: #{@author}" end uses puts, which returns nil.
  3. Final Answer:

    def to_s "Title: #{@title}, Author: #{@author}" end -> Option B
  4. Quick Check:

    Return string with instance variables interpolated [OK]
Hint: Return string with #{@var}, don't print inside to_s [OK]
Common Mistakes:
  • Using variable names without @ inside strings
  • Printing inside to_s instead of returning string
  • Not interpolating variables, printing literal text
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard