Recall & Review
beginner
What does the
to_s method do in Ruby?The
to_s method converts an object into its string representation. It is used to get a readable string version of an object.Click to reveal answer
intermediate
How do you override the
to_s method in a Ruby class?You define a <code>to_s</code> method inside your class that returns the string you want to represent the object with. For example:<br><pre>def to_s
"My object as string"
end</pre>Click to reveal answer
beginner
What is the default behavior of
to_s if not overridden?By default, <code>to_s</code> returns a string with the object's class name and an encoding of its object id, like <code>#<ClassName:0x00007fffe1234567></code>.Click to reveal answer
beginner
Why is overriding
to_s useful?Overriding
to_s makes objects easier to read when printed or logged. It helps show meaningful information instead of a generic object id.Click to reveal answer
beginner
Example: What will this code print?<br><pre>class Person
def initialize(name)
@name = name
end
def to_s
"Person named #{@name}"
end
end
p = Person.new("Anna")
puts p.to_s</pre>It will print:<br>
Person named Anna<br>This is because the
to_s method returns that string.Click to reveal answer
What does the
to_s method return by default if not overridden?✗ Incorrect
By default,
to_s returns a string like #<ClassName:0x00007fffe1234567> showing class and object id.How do you customize the string shown when printing an object?
✗ Incorrect
Overriding
to_s lets you define what string represents the object.What will
puts object call internally in Ruby?✗ Incorrect
puts calls to_s on the object to get its string form.If you want to show a person's name when printing their object, what should you do?
✗ Incorrect
Defining
to_s to return the name makes printing the object show the name.Which of these is a valid
to_s method in Ruby?✗ Incorrect
to_s must return a string. Returning "Hello" is correct. Using puts or print inside to_s returns nil.Explain what the
to_s method does and why you might want to override it in your Ruby classes.Think about how objects appear when you use puts.
You got /4 concepts.
Write a simple Ruby class with a
to_s method that returns a custom string describing the object.Use a name or attribute to show in the string.
You got /4 concepts.