Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "p" in Ruby?

I'm sure it's a silly question to those who know, but I can't find an explanation of what it does or what it is.

CSV.open('data.csv', 'r') do |row|   p row end 

What does "p row" do?

like image 783
James P. Wright Avatar asked Nov 18 '09 19:11

James P. Wright


People also ask

What is P method in Ruby?

As already mentioned, in ruby the method p can come in handy when you are trying to figure out what a certain line of code does, what's assigned to a variable, or what a method call returns. As it tells you exactly what you are looking at.

What is the difference between P puts and print in Ruby?

puts and print The puts (short for "out*put s*tring") and print commands are both used to display in the console the results of evaluating Ruby code. The primary difference between them is that puts adds a new line after executing, and print does not.

What does :+ mean in Ruby?

inject accepts a symbol as a parameter, this symbol must be the name of a method or operator, which is this case is :+ so [1,2,3]. inject(:+) is passing each value to the method specified by the symbol, hence summing all elements in the array.

What is the difference between puts and print?

Hi, The difference between print and puts is that puts automatically moves the output cursor to the next line (that is, it adds a newline character to start a new line unless the string already ends with a newline), whereas print continues printing text onto the same line as the previous time.


2 Answers

p() is a Kernel method

It writes obj.inspect to the standard output.

Because Object mixes in the Kernel module, the p() method is available everywhere.

It's common, btw, to use it in poetry mode, meaning that the parens are dropped. The CSV snippet can be written like...

CSV.open 'data.csv', 'r' do |row|   p row end 

It's documented here with the rest of the Kernel module.

like image 193
DigitalRoss Avatar answered Oct 21 '22 08:10

DigitalRoss


Kernel#p is the little debugging brother of Kernel#puts: it more or less works exactly like it, but it converts its arguments using #inspect instead of #to_s.

The reason why it has such a cryptic name is so that you can quickly throw it into an expression and take it out again when debugging. (I guess it's a lot less useful now that Ruby is getting better and better "proper" debugging support.)

Some alternatives to Kernel#p are Kernel#pp (pretty print) from the pp standard library and Kernel#y (YAML) from the yaml standard library.

like image 34
Jörg W Mittag Avatar answered Oct 21 '22 08:10

Jörg W Mittag