Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redo classes slides #81

Open
nerdinand opened this issue Dec 21, 2020 · 0 comments
Open

Redo classes slides #81

nerdinand opened this issue Dec 21, 2020 · 0 comments
Assignees

Comments

@nerdinand
Copy link
Member

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
@nerdinand nerdinand self-assigned this Dec 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant