Created
October 7, 2017 21:54
-
-
Save khan-hasan/ef258d3e6d8323de9bdb21a5a08b27e8 to your computer and use it in GitHub Desktop.
CF 3.4 | simple ruby Cat class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Cat | |
| attr_reader :color, :breed, :name | |
| # There is no need for a separate attr_writer and separate attr_reader for name because attr_accessor can combine those methods into one (DRY) | |
| # attr_writer :name | |
| attr_accessor :name | |
| def initialize(color, breed) | |
| @color = color # Instances variables are available to other methods inside of this class. This is unlike local variables, which only exist inside the method they're called in. | |
| @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 | |
| def speak | |
| puts "Meow!" | |
| end | |
| end | |
| 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 # if the class has not attr_reader, this returns and error because 'color' is an undefined method for class Cat. When an attr_reader is added to the class, the error goes away. | |
| # kitty.color = "orange" # this will return an error if the Cat class doesn't have an attr_writer | |
| puts "Let's give our new cat a name" | |
| kitty.name = "Betsy" | |
| puts kitty.name | |
| puts "Is our cat hungry now?" | |
| kitty.hungry? | |
| puts "Let's fed our cat" | |
| kitty.feed("tuna") | |
| puts "Is our cat hungry now?" | |
| kitty.hungry? | |
| puts "Our cat can make noise" | |
| kitty.speak |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment