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_sWhat will be printed?
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
Remember, to_s returns a string representation of the object.
The to_s method is overridden to return a formatted string showing the name and price. So puts item.to_s prints Item: Book, Price: $15.
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 pWhat will be printed?
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
When you puts an object, Ruby calls to_s automatically.
The to_s method returns a string describing the person. So puts p prints Alice is 30 years old.
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_sWhat error will this code raise?
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
Check variable names inside string interpolation.
The to_s method uses #{price} but price is not defined as a local variable or method. It should be #{@price}. This causes a NameError.
Why do Ruby programmers override the to_s method in their classes?
Think about what puts object shows by default.
Overriding to_s lets you control what string appears when the object is printed or converted to a string. This helps make output clearer and more useful.
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_sWhat will be printed?
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
Each to_s returns a string, so nested calls build the full string.
The Line class's to_s calls to_s on its Point objects, which return coordinates in parentheses. So the output is Line from (1, 2) to (3, 4).