Ruby: to_s vs inspect

Tech - RubyCademy
RubyCademy
Published in
1 min readMar 9, 2018

puts and interpolation

The putsmethod implicitly calls the to_s method of the object passed as parameter (except for a String)

class Factory
def initialize
@workers = { workers: [] }
@machines = { machines: [] }
end
def add_worker(name)
@workers[:workers] << { :name => name }
end

def add_machines(id)
@machines[:machines] << { :id => id }
end

def to_s
ws = @workers[:workers].map { |w| w[:name] }.join(', ')
ms = @machines[:machines].map { |m| m[:id] }.join(', ')

<<-EOF
Worker Names[#{@workers[:workers].count}]: #{ws}
Machine IDs[#{@machines[:machines].count}]: #{ms}
EOF
end
end
factory = Factory.new
factory.add_worker('Jim')
factory.add_worker('Larry')
factory.add_worker('Doug')
factory.add_machines('12QC-2323')
factory.add_machines('12QC-2324')
factory.add_machines('12QC-2325')

So, a call to puts with factory as parameter will implicitly call factory.to_s

> puts factory
Worker Names[3]: Jim, Larry, Doug
Machine IDs[3]: 12QC-2323, 12QC-2324, 12QC-2325

to_s is also implicitly called during String interpolation

> "#{factory}"
" Worker Names[3]: Jim, Larry, Doug\n Machine IDs[3]: 12QC-2323, 12QC-2324, 12QC-2325\n"

inspect

The inspect method returns a String that represents the calling object

[1,2,3].inspect # "[1,2,3]"

It’s also implicitly called by the p method

p [1,2,3] # "[1,2,3]"

Conclusion

to_s is usually used for logging purposes.

inspect is usually used for debugging purposes.

Ruby Mastery

We’re currently finalizing our first online course: Ruby Mastery.

Join the list for an exclusive release alert! 🔔

🔗 Ruby Mastery by RubyCademy

Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.

💚

--

--