Last active
August 29, 2015 14:15
-
-
Save launchkit-codes/a3a08bcc7340f5fec0de to your computer and use it in GitHub Desktop.
`p` and `puts` Behind The Scene
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # `puts` method calls `to_s` method when a class is given as param | |
| # `p` method calls `inspect` method when a class is given as param | |
| class Factory | |
| def initialize | |
| @workers = { workers: [] } # A lot of workers | |
| @machines = { machines: [] } # A lot of machines | |
| end | |
| def add_worker(name) | |
| @workers[:workers] << { :name => name } | |
| end | |
| def add_machines(id) | |
| @machines[:machines] << { :id => id } | |
| end | |
| def to_s | |
| w = @workers[:workers].map { |worker| worker[:name] }.join(', ') | |
| m = @machines[:machines].map { |machine| machine[:id] }.join(', ') | |
| "Worker List: #{w} -- Machine List: #{m}" | |
| end | |
| def inspect | |
| "You're trying to dig :)" | |
| 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') | |
| puts factory | |
| p factory | |
| # Output: | |
| # | |
| # $> ruby display_complex_objects.rb | |
| # Worker List: Jim, Larry, Doug -- Machine List: 12QC-2323, 12QC-2324, 12QC-2325 | |
| # You're trying to dig :) | |
| # $> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment