0
0
Rubyprogramming~10 mins

To_s method for string representation in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - To_s method for string representation
Object created
Call to_s method
to_s returns string
String used for output or display
This flow shows how calling the to_s method on an object returns its string form for display or output.
Execution Sample
Ruby
class Person
  def initialize(name)
    @name = name
  end
  def to_s
    "Person: #{@name}"
  end
end

p = Person.new("Alice")
puts p.to_s
This code creates a Person object and prints its string representation using the to_s method.
Execution Table
StepActionEvaluationResult
1Create Person object with name 'Alice'Person.new("Alice")Object p with @name = 'Alice'
2Call p.to_sp.to_s"Person: Alice"
3puts prints the stringputs "Person: Alice"Output: Person: Alice
💡 to_s method returns string, printed by puts, program ends
Variable Tracker
VariableStartAfter 1Final
pnilPerson object with @name='Alice'Person object with @name='Alice'
@namenil'Alice''Alice'
Key Moments - 2 Insights
Why does calling to_s on the object return a readable string?
Because the to_s method is defined in the Person class to return a formatted string using the @name variable, as shown in step 2 of the execution_table.
What happens if we don't define to_s in the class?
Ruby uses the default to_s method from Object class, which returns an unreadable string like "#<Person:0x00007f...>", not a friendly name. This is why step 2's result would differ.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output of p.to_s at step 2?
A"Alice"
B"Person: Alice"
C"#<Person:0x00007f...>"
Dnil
💡 Hint
Check the 'Result' column in row 2 of the execution_table.
At which step does the program print the string to the screen?
AStep 1
BStep 2
CStep 3
DAfter program ends
💡 Hint
Look for the step where puts is called in the execution_table.
If we remove the to_s method from Person class, what would p.to_s return?
AA default object string like "#<Person:0x00007f...>"
B"Alice"
C"Person: Alice"
DAn error
💡 Hint
Refer to key_moments explanation about default to_s behavior.
Concept Snapshot
to_s method returns a string representation of an object.
Define to_s in your class to customize output.
Called automatically in string contexts.
Default to_s shows object id, not friendly.
Use puts obj.to_s to print readable info.
Full Transcript
This example shows how the to_s method works in Ruby. First, a Person object is created with the name 'Alice'. Then, calling p.to_s runs the to_s method defined in the Person class, which returns the string "Person: Alice". Finally, puts prints this string to the screen. If to_s was not defined, Ruby would print a default object string instead. This method helps show objects in a friendly way.