What is p in Ruby?
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.
p vs puts in Ruby
p foo
prints foo.inspect
followed by a newline, i.e. it prints the value of inspect
instead of to_s
, which is more suitable for debugging (because you can e.g. tell the difference between 1
, "1"
and "2\b1"
, which you can't when printing without inspect
).
Difference between p in a rails view and puts
puts
calls the method to_s
p
calls the method inspect
class Foo
def to_s
"In #to_s"
end
def inspect
"In #inspect"
def
def
Semantically, to_s is meant to output the representation of the object to the user, and inspect to hint about the internal properties of the object (kinda like python's repr
), but that's just a convention.
If you want to inspect something in your HTML use <%= debug "something" %>
What is difference between p and pp ?
p
is used to inspect a variable as a debug aide. It works printing the output of the method #inspect
. For example p foo
will output the content of foo.inspect
.
Sometimes you need to debug complex variables or nested variables. In this case p
will output a long line that is hard to understand. Instead, pp
will put try to arrange the content of the variable so that it is easier to understand, for example indenting nested arrays or using one line for each instance variable of a complex object. pp
does this calling the #pretty_inspect
method (the pp
library adds #pretty_inspect
methods to many classes such as String
, Array
or Struct
).
To remember: p
= print, pp
= pretty print.
Where does the variable p get it's value from in ruby if it's not defined explicitly?
p
is just a method on Kernel
which calls inspect
on its arguments, producing human-readable representations of those objects. If you give it no arguments, it prints nothing. Regardless of what you pass it, though, it returns nil
. See Kernel#p
and Object#inspect
.
Power tip: In Ruby 1.9, when you have a method and you don't know where it came from, use the method
method:
ruby-1.9.1-p378 > method(:p)
=> #<Method: Object(Kernel)#p>
Putting it together one step at a time, we read this as:
p # We found a method called p.
#p # It's an instance method.
Object ... #p # It's available on Object.
Object(Kernel)#p # It came from the Kernel module.
Update: The OP provided some context from this article, where the author claims that your life will be easier if you add a method_missing
to nil
, by doing the following:
def p.method_missing*_;p;end
This somewhat obfuscated code should be read as:
- Define a new method (
def
), calledmethod_missing
. This overrides the defaultmethod_missing
handler onObject
, which simply raises aNoMethodError
when it encounters a method it doesn't understand. - This method will live on something called
p
. - It accepts any number of arguments (
*
) and stores them in a variable called_
. - The result of these arguments is something called
p
.
The second bullet is the tricky part here. def p.method_missing
means one of two things, depending on context:
- A previously defined object called
p
which is in scope here. - A method called
p
which is in scope, and which is passed no arguments.
With def p.method_missing
, we mean, "this method is being defined on the object which is the result of calling p
with no arguments". In this case, that is NilClass
; if you call p
with no arguments, you get nil
. So this is just a short, hacky way to define a method on NilClass
.
Note: I definitely recommend against defining a method_missing
on nil
. This is a silly and dangerous tactic to use for the sake of saving a few lines of code, because it changes the behavior of nil
. Don't do it!
What is the difference between print and puts?
puts
adds a new line to the end of each argument if there is not one already.
print
does not add a new line.
For example:
puts [[1,2,3], [4,5,nil]]
Would return:
1
2
3
4
5
Whereas print [[1,2,3], [4,5,nil]]
would return:
[[1,2,3], [4,5,nil]]
Notice how puts does not output the nil value whereas print does.
ruby: what does the asterisk in p *1..10 mean
It's the splat operator. You'll often see it used to split an array into parameters to a function.
def my_function(param1, param2, param3)
param1 + param2 + param3
end
my_values = [2, 3, 5]
my_function(*my_values) # returns 10
More commonly it is used to accept an arbitrary number of arguments
def my_other_function(to_add, *other_args)
other_args.map { |arg| arg + to_add }
end
my_other_function(1, 6, 7, 8) # returns [7, 8, 9]
It also works for multiple assignment (although both of these statements will work without the splat):
first, second, third = *my_values
*my_new_array = 7, 11, 13
For your example, these two would be equivalent:
p *1..10
p 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Topics
Problems with the Rails Console, Rvm and Readline
How to Print Out the Contents of an Object in Rails for Easy Debugging
How to Decompress Gzip String in Ruby
Confusion About Passing Instance Variables to Redirect_To Method. as Seen in Rails Guides
Installing Jekyll on Ubuntu 14.04
Split String into a List, But Keeping the Split Pattern
Has_Many :Through with Counter_Cache
Merging Multi-Dimensional Hashes in Ruby
Passing Multiple Error Classes to Ruby's Rescue Clause in a Dry Fashion
How to Pass a Parameter for Gem Installation When I Run Bundle Install
How Does Shovel (<<) Operator Work in Ruby Hashes
What's the Difference Between Gem_Home and Gem_Path
Put a Link in a Flash[:Notice]
How to Dynamically Alter Inheritance in Ruby
Ruby: Accessing Rake Task from a Gem Without Rails
Capturing Groups Don't Work as Expected with Ruby Scan Method