Comprehensive Ruby Programming
上QQ阅读APP看书,第一时间看更新

Using p

Another way to print to the console is as follows:

p "B string" 

The difference between these two methods is that the former method will not return any value back to you, whereas the latter one will return a value. The following image shows this difference:

You will see that the puts method returns a value of nil:

The second option returns the value.

Though this difference may not be much now, you will discover how important this is as we progress through the course.

Another difference between the two methods is the way they process the array data structure. The p method prints the array in its code form and returns these values back to the user:

On the other hand, the puts method iterates through the collection to display individual values, and as mentioned earlier, this returns a nil value:

The first set of values were printed with the method.

Knowing that both of these methods work with all data types including arrays and collections is important. Understanding these similarities and differences is important, to ensure that you use the right method at the right time.