×

ruby · level 2 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.