typestar

Classes and attr_reader in Ruby

A minimal class: initialize, instance variables and readers.

class Card
  attr_reader :rank, :suit

  def initialize(rank, suit)
    @rank = rank
    @suit = suit
  end

  def to_s
    "#{rank} of #{suit}"
  end
end

card = Card.new("ace", "spades")
puts card
puts card.rank

How it works

  1. attr_reader writes the getter methods so you do not.
  2. initialize runs on new and stores state in @ variables.
  3. Defining to_s lets puts print the object sensibly.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
191
Tokens
53
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 35 seconds.

Type this snippet

Step 1 of 3 in Classes & modules, step 19 of 29 in Language basics.

← Previous Next →