Ruby Question Marks and Exclamation Points

The past month or two I’ve been digging into Ruby and Rails. Along the way I’ve had a few “ah ha!” moments that I figured I would share here in hopes to help save time for others who are trying to pick up the language.

What They Mean

When working with a method that returns a boolean value, it is common to end the method with a “?” to show that the data type expected back is true/false.

The “!” is often used to show that a method is going to change the class rather just return a modified copy of the class.  They are used for more than just this, and I later realized they are actually being used to show that the method is doing something that might be unexpected or potentially dangerous.

What’s Confusing About Them

When starting out with Ruby you see the “?” and “!” thrown on to the end of methods all over the place.  After seeing them in context a few times it’s pretty easy to think that you have grasped their meaning and even start using them on your own without much trouble.

I first started using these characters assuming that I could toss them on the end of my methods to:

  • Return a modified the class rather than return a modified copy of the class (!)
  • Return a boolean value (?)

The “?” and “!” are not special characters (well, sort of… but you know what I mean.) and they do nothing to affect the methods they are appended to.  They are simply part of the method names and have become widely adopted as a naming convention for methods that perform certain actions.  Take a look at the Ruby docs and see for yourself that delete is not the same as delete? and downcase !downcase!, they are completely separate methods.

What This Means For You

Because these characters are simply used as a naming convention for Ruby methods, you can use them in your own classes to provide more meaning to your method names and make it easier to see what’s happening in your code.

As stated earlier, I’m new to Ruby and this is probably common knowledge to anyone who has worked with the language for a reasonable amount of time.  It’s just something that I didn’t understand at first so I figured I would share here to hopefully shed some light for others trying pick up Ruby.