×

ruby · level 2 · unit 6 · lesson 2

  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

sets up each new object with its own data.

When you call .new, Ruby runs a method called initialize inside the new object. Any arguments you give .new are passed on to it, so Pet.new("Rex", 3) hands it a name and an age.

An starts with @, like @name. It belongs to one object and lasts as long as that object, so every method in the class can use it. Two pets each have their own @name.

class Pet
  def initialize(name, age)
    @name = name
    @age = age
  end
  def describe
    "#{@name} is #{@age}"
  end
end
[Pet.new("Rex", 3), Pet.new("Tilly", 7)].each { |pet| puts pet.describe }

A plain variable inside a method vanishes at its end, but an instance variable stays with the object.