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
attr_readerwrites the getter methods so you do not.initializeruns onnewand stores state in@variables.- Defining
to_sletsputsprint the object sensibly.
Keywords and builtins used here
Cardclassdefendinitializeputsto_s
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.
Step 1 of 3 in Classes & modules, step 19 of 29 in Language basics.