Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Pet
- attr_reader :color, :breed # Be able to read these instance variables outside of the instance
- attr_accessor :name # Be able to both read & write this instance variable outside of the instance
- def initialize(color, breed) # Initialize instance variables
- @color = color
- @breed = breed
- @hungry = true
- end
- def feed(food)
- puts "Mmmm, " + food + "!"
- @hungry = false
- end
- def hungry?
- if @hungry
- puts "I'm hungry!"
- else
- puts "I'm full!"
- end
- @hungry
- end
- end
- class Cat < Pet
- def speak
- puts "Meow!"
- end
- end
- class Dog < Pet
- def speak
- puts "Woof!"
- end
- end
- puppy = Dog.new("black", "Staffordshire Terrier")
- puppy.speak
- puts puppy.breed
- kitty = Cat.new("grey", "Persian")
- puts "Let's inspect our new cat:"
- puts kitty.inspect
- puts "What class does our new cat belong to?"
- puts kitty.class
- puts "Is our new cat an object?"
- puts kitty.is_a?(Object)
- puts "What color is our cat?"
- puts kitty.color
- puts "Let's give our new cat a name."
- kitty.name = "Maceo"
- puts kitty.name
- puts "Is #{kitty.name} hungry now?" # Added string interpolation because it's weird to keep referring to "our cat" after naming it.
- kitty.hungry?
- puts "Let's feed #{kitty.name}."
- kitty.feed("tuna")
- puts "Is #{kitty.name} hungry now?"
- kitty.hungry?
- puts "#{kitty.name} can make some noise."
- kitty.speak
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement