Question: Where does p get it’s value from below and why does it happen?
Consider this irb session:
me@somewhere:~$ irb
irb(main):001:0> a
NameError: undefined local variable or method `a' for main:Object
from (irb):1
irb(main):002:0> foo
NameError: undefined local variable or method `foo' for main:Object
from (irb):2
irb(main):003:0> p
=> nil
irb(main):004:0> p.class
=> NilClass
irb(main):005:0>
I never defined p – so why is it nil valued? Neither a nor foo were recognized so what’s special about p? I also didn’t find anything listed under Kernel#p
Context: I’m reading the so-called “28 bytes of ruby joy” and assumed p was a variable, as in: def p.method_missing *_ …
(Don’t worry: I’m not going to actually define method_missing on nil everywhere… just studying some ruby code…)
pis just a method onKernelwhich callsinspecton 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 returnsnil. SeeKernel#pandObject#inspect.Power tip: In Ruby 1.9, when you have a method and you don’t know where it came from, use the
methodmethod:Putting it together one step at a time, we read this as:
Update: The OP provided some context from this article, where the author claims that your life will be easier if you add a
method_missingtonil, by doing the following:This somewhat obfuscated code should be read as:
def), calledmethod_missing. This overrides the defaultmethod_missinghandler onObject, which simply raises aNoMethodErrorwhen it encounters a method it doesn’t understand.p.*) and stores them in a variable called_.p.The second bullet is the tricky part here.
def p.method_missingmeans one of two things, depending on context:pwhich is in scope here.pwhich 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 callingpwith no arguments”. In this case, that isNilClass; if you callpwith no arguments, you getnil. So this is just a short, hacky way to define a method onNilClass.Note: I definitely recommend against defining a
method_missingonnil. This is a silly and dangerous tactic to use for the sake of saving a few lines of code, because it changes the behavior ofnil. Don’t do it!