Ruby Classes Lab
Remember:
- Ruby objects are created by Ruby classes
- A Ruby class is a template for creating a Ruby object
- A Ruby object contains methods from its class and maintains its own state
Make an object from a class by using
some_new_object = SomeClass.new (optional arguments)1. Classes
Watch the optional short video here. 6 mins 23 seconds.
Create Muppets
- Create a
Muppetclass that takes in anameand runputs "This muppet is called #{name}!"insideinitialize. - Assign the muppet a random color on
initialize. Hint: make a small array and use.sample
Create Birds
- Create a
Birdclass that takes in anadjectiveand anameandputs"#{name} is a(n) #{adjective} bird!"insideinitialize. - Assign the bird a species at random on
initialize. Hint: make a small array and use.sample - Here is an array of bird species, for your convenience
['Belted Kingfisher', 'Yellow-Billed Cuckoo', 'White-Cheeked Pintail', 'Cinnamon Teal', 'Lesser Scaup', 'Bufflehead', 'Common Goldeneye', 'Fulvous Whistling Duck', 'Hooded Merganser', 'White-Winged Scoter', 'Chimney Swift', 'Rufous Hummingbird', 'Chuck-Wills-Widow', 'Whip-Poor-Will', 'Albatross', 'Ruddy Turnstone', 'Piping Plover', 'Killdeer', 'Laughing Gull', 'Marbled Godwit', 'Least Tern', 'New World Warbler']2. Methods
Watch the optional short video here here. 8 mins 22 seconds.
Muppet methods
-
Add methods to your
Muppet- Add a
honkmethod to your muppet that puts"#{name} is making a honking sound!". Test that it works, comment out your test code. - Test the following to make sure it gives the expected output:
- Add a
q = Muppet.new("K-Rad")
q.honk- Add a
flailmethod that puts"#{name} is flailing its arms!". Test that it works.
Bird methods
-
Add methods to your
Bird- Add a
hungrymethod that puts"#{name} wants some regurgitated worms!". Test that it works. - Add a
flymethod that puts"Flap! #{name} is taking flight!". Test that it works.
- Add a
- Make your bird's
adjectiveandnameaccessible (both reading and writing). Test that this works.
3. Inheritance
Watch the short video here. 6 mins 56 seconds.
Exercises:
- Create a class called
Dessertthat has instance variables of@nameand@sugar_content - Give it an instance method of
eatthat puts"Yum! This #{name} is sooooo delicious!" - Make two new classes called
PieandDeepFriedDessertthat inherit fromDessert - Give the
DeepFriedDessertits owneatmethod that instead puts"Yum! This #{name} is sooo...ack! ugh! *heart-attack*" - Make a new class
IceCreamthat inherits fromDessert. Usesuperto get the instance variables of@nameand@sugar-content. Also giveIceCreamits own unique instance variable of@toppings
4. The Universe
Reps with Classes
Universe Part One
What's in a Class? A class can contain any number of variables and any number of methods. That is, any number of things and any number of actions. Therefore, let's make a Universe simulator! ;)
- Make a Class called
Universe. Universetakes three parameters,item1,item2,item3: these are the three things within this universe we are making-- they could be anything: suns, galaxies, dust, people, lossless mp3s, justice, temporal lobes, etc. Save these things into an array called@items.- Give the
initializemethod an instance variable@expanding = true - Give the
initializemethod an instance variable@conservation = true - Give the
initializemethod an instance variable@crunched = false - Make a method
see_all_thingsthat will print out all the items in this universe. Test it out. - Make a method called
createthat takes a parameternew_itemand will add the new item to the universe (in the@itemsarray). If@conservation = truethen one random item in the universe is replaced by the new thing. If not, then a new thing is added to the@itemsarray.
Universe Part Two
- While
@conservationis true, run thecreatemethod to add a "mosquito" to your universe. Keep running it until all of the items in your universe are mosquitoes (they should be randomly replaced). You now have a mosquito universe. :( - Time to make a parallel universe. Make a new instance of your universe called
parallel, and put three new things into it. - Make a method
check_densitythat changesexpandingtofalseif there are more than ten things in the universe (more than ten items in the@itemsarray). This will mean that the universe is now contracting under its own gravity. We'll come back to this in a minute . . . - Make a method called
energy_conservationthat changesconservationfromtruetofalseif all items in the@itemsarray are identical. Hint: check out the.uniqmethod.
Universe Part Three
- Make a method called
crunch?wherein, ifexpandingequalsfalse, goes through each item in the@itemsarray, sets it toniland prints a string saying the name of the item and that it has been crunched due to gravity. When the entire contents of the array arenil, set the array itself toniland print "The Universe has ended." If the universe has ended, set@crunchedtotrue. -
Write your Universal Simulator that runs the following steps in a loop until the Universe has ended. The Universe has ended when
@crunchedistrue. You might want to make@crunchedavailable withattr_accessor. Start by making a new instance of the Universe.- print the contents of
@items - add an item to
@items - check conservation
- check density
- crunch?
- print the contents of
Possible output:
spam
github
lava
spam has been crunched due to gravity
github has been crunched due to gravity
lava has been crunched due to gravity
radio waves has been crunched due to gravity
The Universe has ended
=> trueHUNGRY FOR MORE?
5. Class Methods and 'Self'
Watch the short video here. 8 mins 28 seconds.
Exercises:
-
Experiment with
self- Add a class method
self.what_is_selfto yourMuppetclass and have itp self. - Add an instance method
what_is_selfto your Muppet class and have itp self. - Try calling both of these methods in Pry and see what they return.
- Add a class method
-
Add a class method to make baby Muppets
- In your
Muppetclass, add an instance variable that gives your Muppet a characteristic or quality such as 'zany', 'quiet', 'twitchy' to the instance of the Muppet. - Add a class method of
self.make_muppetto yourMuppetclass that takes in two Muppets and returns a new Muppet. - The new Muppet should have the color of the first Muppet and the quality of the second Muppet. Make some Muppets.
- In your