Sonntag, 8. März 2015

Avoid get or set prefixes in Ruby method names!

Getter and setter methods marked with get or set as prefix are from Java land, because it is an inflexible language.
Ruby is flexible and therefore provides a more concise way. A Javaish looking:
class Person
  def get_age
    @age
  end

  def set_age age
    @age = age
  end
end
should be refactored to:
class Person
  def age
    @age
  end

  def age= age
    @age = age
  end
end
Apart from using attr_accessor in those simple cases, it allows to send a more meaningful message:
person = Person.new
person.age = 30
person.age

Supported by Ruby 2.1.1