Richard Conroy
10/5/2006 7:48:00 PM
On 10/5/06, py <codecraig@gmail.com> wrote:
> what does the question mark at the end of a method name represent?
Unlike other languages which generally only permit alphanumerics in
method names, Ruby allows the use of a limited number of punctuation
characters to pad out function names.
This isn't a special syntax. There are plenty others too.
By convention, the trailing '?' in a method definition signifies that this
function call will return a boolean value, and its a wonderfully expressive
and pleasant way to do this. Little things like this make people love
languages.
The '!' is a bit different - its generally used to indicate that calling the
function can change the objects state or modify it (if you weren't
really expecting it). The convention isn't as tight, and the APIs
usually offer you a safe version of the same function too.
I guess that omitting a '?' from a function that returns exclusively
boolean values would be considered bad Ruby style.
I am on shaky ground here, personally, but I believe Ruby's way
of doing operators uses the same thing. If you look at the '<<'
operator (which does 'append to me') in say the string or array
class, you will find a method defintion like this:
def <<(variable)
#implementation of append e.g.
concat(variable)
end
So you should be doing wierd stuff like:
String.<<(anotherString)
but Ruby steps in with some syntactic sugar
and you can drop all the punctuation:
String << anotherString
The rules are probably similar for the other operators,
like FixNum probably has a definition like this
def + anotherFixNum
....
end
(this is the bit where my mouth runs off and leaves my
knowledge behind)
Basically when you are used to other languages that stuff
looks really wierd - it doesn't even look like a proper
definition, but once you understand it, its really elegant:
"Oh the plus sign is the *name* of the function? Neat."