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.
class Person def initialize(name) @name = name end def to_s "Person: #{@name}" end end p = Person.new("Alice") puts p.to_s
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create Person object with name 'Alice' | Person.new("Alice") | Object p with @name = 'Alice' |
| 2 | Call p.to_s | p.to_s | "Person: Alice" |
| 3 | puts prints the string | puts "Person: Alice" | Output: Person: Alice |
| Variable | Start | After 1 | Final |
|---|---|---|---|
| p | nil | Person object with @name='Alice' | Person object with @name='Alice' |
| @name | nil | 'Alice' | 'Alice' |
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.