Why do this Ruby object both a to_s
and inspect
methods that appear to do the same thing?
The p
method calls inspect
and puts/print calls to_s
for representing the object.
If I run
class Graph def initialize @nodeArray = Array.new @wireArray = Array.new end def to_s # called with print / puts "Graph : #{@nodeArray.size}" end def inspect # called with p "G" end end if __FILE__ == $0 gr = Graph.new p gr print gr puts gr end
I get
G Graph : 0 Graph : 0
to_s
and inspect
?puts
, print
, and p
?If I comment out the to_s
or inspect
function, I get as follows.
#<Graph:0x100124b88> #<Graph:0x100124b88>
inspect is a String class method in Ruby which is used to return a printable version of the given string, surrounded by quote marks, with special characters escaped.
When you call Song. new to create a new Song object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new . This gives you a chance to write code that sets up your object's state.
Practically everything in Ruby is an Object, with the exception of control structures. Whether or not under the covers a method, code block or operator is or isn't an Object, they are represented as Objects and can be thought of as such.
In `ruby`, the body of an object is expressed by a struct and always handled via a pointer. A different struct type is used for each class, but the pointer type will always be `VALUE` (figure 1). In practice, when using a `VALUE`, we cast it to the pointer to each object struct.
inspect
is used more for debugging and to_s
for end-user or display purposes.
For example, [1,2,3].to_s
and [1,2,3].inspect
produce different output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With