Main Content

Exclamation marks and question marks on ruby method names

Archive - Originally posted on "The Horse's Mouth" - 2010-07-28 07:46:43 - Graham Ellis

In ruby, you'll find some function/method names that are just a series of letters (a rather conventional sort of name for a function or a variable), and others that have a ! or ? on the end. What's the significance of these?

• A function with a ! on the end usually alters the incoming object rather than returning a new object
• A function with a ? on the end usually return a true or false value so would be used in a conditional
• A function with neither a ? nor a ! usually returns a new object.

Here's an example with chop ...

This will not alter stuff, but will return you a result object in less:
  less = stuff.chop
whereas this will alter the stuff object:
  stuff.chop!

There's a further example [here] - including sample output