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.
to_s method do in Ruby?to_sto_s method is used to convert any Ruby object into a string format.to_s means convert to string [OK]to_s method in a Ruby class?to_s must be exactly that, with underscore and lowercase.to_s [OK]to_s with underscore [OK]class Person
def initialize(name)
@name = name
end
def to_s
"Person named #{@name}"
end
end
p = Person.new("Alice")
puts p.to_sto_s methodto_s to return "Person named #{@name}", where @name is set to "Alice".puts p.to_s printsp.to_s returns "Person named Alice", which is printed by puts.to_s returns formatted string [OK]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_sto_smodel without @, but the instance variable is @model.model, which does not exist, causing an error.Book that stores a title and author, and when printed, shows "Title: [title], Author: [author]". Which to_s method correctly achieves this?#{@title} and #{@author} inside the string.to_sto_s should return a string, not print it. def to_s
puts "Title: #{@title}, Author: #{@author}"
end uses puts, which returns nil.Pass the test and this pattern moves unknown