Can someone please explain the ? usage as I have searched all over the
Pragmatic Programmer pages with no answer.
That’s just a part of the method name. Run “irb” and paste this
into it:
class Monkey
def hasFleas?
true
end
end
class Rking
def hasFleas?
false
end
end
Monkey.new.hasFleas?
Rking.new.hasFleas?
You will find that Monkeys have fleas while Rking’s decidedly do
NOT.
Anyway, the point is: Putting a question mark at the end of a
method name is a custom to imply that the method returns a
boolean.
Ryan
__
This e-mail and any attachments may be confidential or legally privileged.
If you received this message in error or are not the intended recipient, you
should destroy the e-mail message and any attachments or copies, and you are
prohibited from retaining, distributing, disclosing or using any information
contained herein. Please inform us of the erroneous delivery by return
e-mail.
This is the price we pay for using funny syntax here and there. =)
In this case (specifically, when * is used as a unary operator),
it is the “splat” operator. Or the “splatsterisk”, if you will.
(Most people won’t).
As an example:
def foo a, b
p a, b
end
foo *[‘don’, ‘key’] # Same as
foo ‘don’, ‘key’ # …this
That is, it peels off the arrayness of the argument. Kind of
funky, but it’s your only recourse sometimes.
And, in a preemptive strike, I’ll answer this one:
def bar first, *rest
p first, rest
end
bar 1, 2, 3, 4
In this case, “*” is serving as an “unsplat” (or “unsplatserisk”,
but almost no one will). It allows you to pass an arbitrary
number of arguments and they all get rolled into one array, in
this case “rest”. It’s like C’s varargs.
Ryan King
P.S.: Sorry for using cliche` metasyntactic method names. I’m
being lazy.