Sonntag, 15. März 2015

Mark boolean methods in Ruby!

Some methods are special. They return a boolean value. Ruby has a convention for them: a question mark at the end.
The code:
class Person
  attr_accessor :age
  def intialize attributes={}
    @age = attributes[:age]
  end

  def is_adult
    @age > 18
  end
end
person = Person.new age: 20
person.is_adult
=> true
What does it express? Does it mean "The person is an adult" or does it ask "Is the person an adult"?
To make things clear the Ruby way is putting a question mark at the methods end:
class Person
  attr_accessor :age
  def intialize attributes={}
    @age = attributes[:age]
  end

  def adult?
    @age > 18
  end
end
person = Person.new age: 20
person.adult?
=> true
Using a question mark for boolean methods leaves no question.

Supported by Ruby 2.1.1