Skip to content

Redo classes slides #81

@nerdinand

Description

@nerdinand

Outline:

# Slide set 1: Creating objects

class Cat
  def speak
    puts "Meow!"
  end
end

cat = Cat.new
cat.speak


class Cat
  def speak(number)
    number.times do 
      puts "Meow!"
    end
  end
end

cat = Cat.new
cat.speak(3)


class MyColours
  def favourite?(colour)
    if colour == "Gray"
      true
    elsif colour == "Blue"
      true
    else
      false
    end 
  end
end

my_colours = MyColours.new
my_colours.favourite?("Green") # => false
my_colours.favourite?("Gray") # => true


# Slide set 2: Objects with data

# "Manual" getters/setters (wrong naming convention)

class Cat
  def set_name(new_name)
    @name = new_name
  end

  def get_name
    @name
  end
end

alice = Cat.new
alice.set_name("Alice")
puts alice.get_name

# interactive slides about local vs. instance variables

brienne = Cat.new
brienne.set_name("Brienne")
puts brienne.get_name

# "Manual" getters/setters (correct naming convention)

class Cat
  def name=(new_name)
    @name = new_name
  end

  def name
    @name
  end
end

class Cat
  def name=(name)
    @name = name
  end
end


# Reader, writer

class Cat
  attr_writer :name
  attr_reader :name
end

# Accessor

class Cat
  attr_accessor :name
end


# Cookie cutter (or other) analogy, class diagram here


# Slide set 3: Objects with initial data

# initialize

class Cat
  def initialize(initial_name)
    @name = initial_name
  end
end

class Cat
  def initialize(initial_name)
    @name = initial_name
    @foods = []
    @pets_today = 0
  end

  attr_reader :name
  attr_accessor :coat

  def eat(food)
    @foods << food
  end

  def pet
    @pets_today += 1
  end

  def happy?
    @foods.any? && pets_today > 10
  end
end


# Slide set 4: Objects passed to objects


class Toy
  def initialize(name)
    @name = name
    @damage_level = 0
  end

  attr_accessor :damage_level, :name

  def broken?
    @damage_level >= 10
  end
end


class Cat
  def play_with(toy)
    toy.damage_level += 1
  end
end

cat = Cat.new
owl = Toy.new("Owl")

cat.play_with(owl)
cat.play_with(owl)
cat.play_with(owl)

puts owl.damage_level # => 3
puts owl.broken? # => false

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions