ruby · level 2 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Open a window onto your object's data.
Code outside a class cannot see @name. writes a little method called name that hands back @name. writes a reader and a writer, so outside code can also say pet.age = 4.
puts calls an object's to_s method to get its text. A new class shows something messy like #<Pet:0x...>, so write your own to_s that hands back a tidy string. Then puts pet and "#{pet}" both read nicely.
class Pet
attr_accessor :name, :age
def to_s
"#{name}, aged #{age}"
end
end
pet = Pet.new
pet.name = "Rex"
pet.age = 4
puts pet Inside the class, name calls the reader, so you can write name instead of @name.
guess first
Reader or writer? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Book
attr_reader :title
def initialize(title)
@title = title
end
end
book = Book.new("Matilda")
puts book.title
book.title = "Holes"
your turn
Your turn. Rate a film.
Fill in a film title and a whole-number rating out of 5, then press run. puts film uses your to_s.
fix it
The football card shows nonsense. Can you fix it?
putsshows a strange code instead of the sentence. Which method doesputslook for?putscalls a method namedto_s. Ruby has never heard ofto_string.- Rename to_string to to_s on line 3, then press run.
nailed it
your objects can introduce themselves. :D
attr_readerlets outside code read a value.attr_accessorlets it read and change the value.- Write
to_ssoputsshows your object nicely.
new words in your collection
- attr_reader
- attr_accessor
This lesson isn’t saved. A free account remembers every lesson you finish.