Verbosity of p

J

Johny Why

hello

why does:
puts "Inspect:#{p(myDog)}"

give LESS verbose results than:

p(myDog)

?

is it that p returns an array, and puts only prints the first element of
arrays?

thanks
 
M

Matthew Bloch

hello

why does:
puts "Inspect:#{p(myDog)}"

give LESS verbose results than:

p(myDog)

?

is it that p returns an array, and puts only prints the first element of
arrays?

"p x" is a shorthand for "puts x.inspect", i.e. it actually does the
printing. The "inspect" method is what actually returns a "verbose"
string. I suspect the intent of your first statement was:

puts "Inspect:#{myDog.inspect}"

If you call p during a string interpolation, you can expect the output
to appear before the whole strong you've asked it to print, which is
probably not what you wanted.
 
B

Ben Bleything

why does:
puts "Inspect:#{p(myDog)}"

give LESS verbose results than:

p(myDog)

The method #p is meant to be used as a replacement for:

puts obj.inspect

It outputs itself, so you don't want to interpolate its output like
you're doing above. Try this:

print "Inspect: "
puts myDog.inspect

... vs ...

print "p: "
p myDog

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top