Ruby punctuation ?!

I noticed that methods in Ruby are sometimes followed by some punctuation characters, particularly the ? and ! characters. Finally took a moment to learn about them, and wanted to share with everyone.

nn

.method!

nn

In Ruby, calling most methods on an object will return a modified version of an object, rather than modifying the object itself. This is known to be “safe”, in that if you unintentionally call a method on an object, you will not have to worry about a potentially dangerous change to a piece of data.

nn

$ irbn2.1.1 :001 > my_string = "Hello, world!"n => "Hello, world!"n2.1.1 :002 > puts my_stringnHello, world!n => niln2.1.1 :003 > my_string.upcasen => "HELLO, WORLD!"n2.1.1 :004 > puts my_stringnHello, world!n => niln

nn

In the code above, we create a string called my_string and set it to the value Hello, world!. We then call the .upcase method on my_string, which prints the string in all upper case letters. However, when we print my_string out again using puts, the string remains in its original format.

nn

Now, let’s try .upcase again, but add the ! at the end:

nn

2.1.1 :005 > my_string.upcase!n => "HELLO, WORLD!"n2.1.1 :006 > puts my_stringnHELLO, WORLD!n => niln2.1.1 :007 >n

nn

my_string was modified to all upper case letters. The contents of the original variable were modified.

nn

.method?

nn

The question mark in Ruby is more of a naming convention than a method modification. The ? is used to denote that the method will return a true or false value. In other programming languages, this convention is typically implemented by adding the is_ or is prefix to the method name. I’ve also seen has_ or has prefix for boolean tests of different sort.

nn

2.1.1 :007 > my_string.empty?n => falsen

nn

Calling .empty on my_string returns false because my_string contains a value (“HELLO, WORLD!”). Note that there is no .empty method on a string:

nn

2.1.1 :008 > my_string.emptynNoMethodError: undefined method `empty' for "HELLO, WORLD!":Stringn    from (irb):8n    from /Users/johnpitchko/.rvm/rubies/ruby-2.1.1/bin/irb:11:in `<main>'n

nn

Unlike the ! operator, you simply can’t add ? to any method name. It is, in fact, part of the method name. Consult RDoc for a list of all method names built into Ruby.

Leave a Reply

Your email address will not be published. Required fields are marked *