What does p mean in each_slice enumeration?

Just out of curiosity, what does the “p ” in enumerable.each_slice mean in Ruby?

For instance:

(1..3).each_slice(2) {|n| pn} 

prints:

 [1, 2] [3] 

and

 (1..3).each_slice(2) {|n| print n} 

prints:

 123 

a

 (1..3).each_slice(2) {|n| puts n} 

prints:

 1 2 3 
+4
source share
2 answers

No magical or strange behavior, p actually refers to Kernel.p

each_slice iterates over a fragment of 2 elements. So:

iteration 1 → n = [1, 2] iteration 2 → n = [3]

The # p kernel writes n.inspect in each iteration, so it writes lines [1, 2] and then [3] , each of which follows a new line.

The # print kernel writes n followed by the value of $, (the default field separator is nil ), so it writes [1, 2] and immediately writes [3]

And finally, Kernel # puts recursively writes each array, followed by a new line. More about this here: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/227540

+6
source

This is a call to the Kernel#p method.

[it] directly writes obj.inspect , followed by the current output record separator to standard program output.

+1
source

All Articles