Freitag, 14. Dezember 2012

Ruby conventions: methods with ? and !

Today I cover the Ruby convention of using a question mark or exclamation mark in method names.
Following the convention eases the readability of Ruby codes.
The question mark is for methods returning boolean values, like:
class Language
  attr_accessor :name

  def initialize(name)
    @name = name
  end
  
  def downcased?
    name == name.downcase
  end
end
and:
language = Language.new "ruby"
language.downcased?
returns:
=> true

Next. The exclamation mark in Ruby methods. In general, methods with trailing "!" indicate that the method will modify the object it's called on. The ones without are called "safe methods", and they return a copy of the orignal with changes applied to the copy, with the callee unchanged. For example:
original = "RUBY"
copy = original.downcase
The variable:
copy
contains:
=> "ruby"
while:
original
is still:
=> "RUBY"
and please compare with trailing "!":
original = "RUBY"
copy = original.downcase!
The variable
copy
contains:
=> "ruby"
So a trailing "!" in a method name should mark that the object itself will be modified, when called. Syntactic sugar!
Supported by Ruby 1.9.3

Keine Kommentare:

Kommentar veröffentlichen