0
0
Rubyprogramming~5 mins

To_s method for string representation in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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>#&lt;ClassName:0x00007fffe1234567&gt;</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?
AA string with the object's class and id
BThe object's integer value
CAn error
DThe object's memory address as a number
How do you customize the string shown when printing an object?
AUse <code>puts</code> with a string argument
BOverride the <code>to_s</code> method
CChange the object's class name
DOverride the <code>print</code> method
What will puts object call internally in Ruby?
A<code>object.to_s</code>
B<code>object.inspect</code>
C<code>object.print</code>
D<code>object.to_i</code>
If you want to show a person's name when printing their object, what should you do?
AOverride the <code>initialize</code> method
BDefine <code>to_i</code> to return the name
CUse <code>print name</code> inside the class
DDefine <code>to_s</code> to return the name
Which of these is a valid to_s method in Ruby?
Adef to_s; puts "Hi"; end
Bdef to_s() return 123 end
Cdef to_s; "Hello"; end
Ddef to_s; print "Hi"; end
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.