Ruby attributes

From wikinotes

instance variables

  • begin with @
  • instance variables are defined in the constructor.
  • they cannot be read/written unless
    • they are declared with an accessor
    • a getter/setter method of the same name is created
class MyClass
  def initialize()
    @unchangeable = "unchangeable"
  end
end

class variables

class MyClass
  @@class_variable = 10
end

attribute accessors

  • attr_reader define instance-vars that can be read outside class
  • attr_writer define instance-vars that can be written outside class
  • attr_accessor define instance-vars that can be read/writen outside class
  • alternatively, you can create getter/setter methods by hand
class MyClass
  attr_reader :readonly_var
  attr_writer :writeonly_var
  attr_accessor :readwrite_var

  def initialize
    @private_var   = 0
    @readonly_var  = 1
    @writeonly_var = 2
    @readwrite_var = 3
  end
end

setters

class MyClass
  attr_accessor :name

  def name=(val)
    @name = val.capitalize
  end
end

getters

  • parentheses are optional in ruby, so getter methods are just regular methods
class MyClass
  attr_accessor :name

  def fullname
    @firstname + " " + @lastname
  end
end