Skip to content
Symbols and attr_*
step 1/6

Reading — step 1 of 6

Learn

~1 min readModules and Classes

Symbols (:foo) are interned strings — stored once, reused everywhere. They're how Ruby names methods, hash keys, and "enum-ish" constants.

:status                   # the symbol :status
:status == :status        # true (same identity)
"foo".to_sym              # :foo
:foo.to_s                 # "foo"

Use symbols for:

  • Hash keys: { name: "Ada", age: 36 }name: is sugar for :name =>
  • Method names in metaprogramming: define_method(:greet) { ... }
  • Status flags: :active, :archived, :pending

attr_accessor / attr_reader / attr_writer auto-generate getters/setters:

class Person
  attr_accessor :name        # generates name and name=
  attr_reader :id            # generates id only (read-only)
  attr_writer :password      # generates password= only
end

p = Person.new
p.name = "Ada"            # via setter
p.name                    # via getter

This is one of those features that makes Ruby code dense — without it, you'd hand-write def name; @name; end and def name=(v); @name = v; end for every field.

self refers to the current instance. In class methods, it refers to the class itself:

class Counter
  @@count = 0
  def self.create        # class method
    @@count += 1
    new
  end
end

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…