Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. class Pet
  2. attr_reader :color, :breed # Be able to read these instance variables outside of the instance
  3. attr_accessor :name # Be able to both read & write this instance variable outside of the instance
  4.  
  5. def initialize(color, breed) # Initialize instance variables
  6. @color = color
  7. @breed = breed
  8. @hungry = true
  9. end
  10.  
  11. def feed(food)
  12. puts "Mmmm, " + food + "!"
  13. @hungry = false
  14. end
  15.  
  16. def hungry?
  17. if @hungry
  18. puts "I'm hungry!"
  19. else
  20. puts "I'm full!"
  21. end
  22. @hungry
  23. end
  24. end
  25.  
  26. class Cat < Pet
  27. def speak
  28. puts "Meow!"
  29. end
  30. end
  31.  
  32. class Dog < Pet
  33. def speak
  34. puts "Woof!"
  35. end
  36. end
  37.  
  38. puppy = Dog.new("black", "Staffordshire Terrier")
  39. puppy.speak
  40. puts puppy.breed
  41.  
  42. kitty = Cat.new("grey", "Persian")
  43.  
  44. puts "Let's inspect our new cat:"
  45. puts kitty.inspect
  46. puts "What class does our new cat belong to?"
  47. puts kitty.class
  48. puts "Is our new cat an object?"
  49. puts kitty.is_a?(Object)
  50. puts "What color is our cat?"
  51. puts kitty.color
  52. puts "Let's give our new cat a name."
  53. kitty.name = "Maceo"
  54. puts kitty.name
  55. puts "Is #{kitty.name} hungry now?" # Added string interpolation because it's weird to keep referring to "our cat" after naming it.
  56. kitty.hungry?
  57. puts "Let's feed #{kitty.name}."
  58. kitty.feed("tuna")
  59. puts "Is #{kitty.name} hungry now?"
  60. kitty.hungry?
  61. puts "#{kitty.name} can make some noise."
  62. kitty.speak
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement