tags:

views:

713

answers:

4

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?

+3  A: 

Why not try it?

>> [1,2,3].each { |d| p d }
1
2
3
thenduks
Actually it calls `#inspect` to its argument first, but close enough ;)
hrnt
True. Removed my 'alias' comment since it's just plain wrong. Maybe more like 'wrapper'.
thenduks
+17  A: 

p() is a Kernel method that write's obj.inspect to the standard output.

Because Object mixes in the Kernel module, the p() method is available everywhere. It's common to use it in poetry mode, meaning that the parens are dropped. (I like poetry mode, for example your CSV snippet can be written without using parens for the open call.)

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

To find the docs for it, go to http://www.ruby-doc.org/core-1.8.7/index.html and look for the p method in the right hand navigation column.

DigitalRoss
+3  A: 

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.

Jörg W Mittag
+1  A: 

The other option for documentation that you already have on your system is the ri command. At any time you can type: ri p or if p is defined in a lot of places (which it is) for central commands you can try ri Kernel.p. Other good bets are Array. or String.

If you end up installing a bunch of gems this will slow down a lot but you can look up the fastri gem which speeds up the lookup process incredibly.

Chuck Vose