Why different outputs?


#1

The following code:

("a".."c").to_a.zip((1..3).to_a)

If you were to output using 'print' the result is: [["a", 1], ["b", 2], ["c", 3]]
If you were to output using 'puts' the result is:
a
1
b
2
c
3

I thought that the print/puts evaluate the value of the expression and then print the result value. I was expecting the latter to print the same thing but on a new line. Can someone clear this up?


#2

No. puts iterates over its arguments, and for each argument, it applies
to_s and then outputs it with a \n appended, unless there is a \n
already.

You can see like this:
puts([1,2])
outputs
1
2

Ronald


#3

Thanks for clearing this up. Where is a good resource to the see the code
behind Roby's core methods like puts/print/each/etc?


#4

Starting point would be i.e. http://ruby-doc.org/core-2.4.0/ where you
could - for instance - enter "puts" in the search field for the methods
further down the page. After locating the method's documentation page,
you find a small link "Toggle the source code" next to the method name.

In most cases however, I find the documentation written below usually
more helpful than the method's source code. In the case of puts, the
description says "If called with an array argument, writes each element
on a new line", which describes the behaviour you are experiencing.

Ronald


#5

Excellent, thank you.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.