Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this post! 🙏

Thank you for your time!

puts and interpolation

The puts method 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

Machine IDs[3]: 12QC-2323, 12QC-2324, 12QC-2325

"

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.

Voilà

May I have your attention please 🎤🎤

Feel free to subscribe here: www.rubycademy.com