Here is my work for Exercise 40.
1. Write some more songs using this and make sure you understand that you’re passing an array of strings as the lyrics.
2. Put the lyrics in a separate variable, then pass that variable to the class to use instead.
I put a few lines of Merry Christmas into an array and assign it to the variable merry_xmas_lyrics. I then create a new Song object by giving it the merry_xmas_lyrics as an argument. This new song object is assigned to the merry_xmas variable. Finally I call the sing_me_a_song method on the merry_xmas song object.
3. See if you can hack on this and make it do more things. Don’t worry if you have no idea how, just give it a try, see what happens. Break it, trash it, thrash it, you can’t hurt it.
I added another argument to the initialize method, now there is a singer argument. I added two methods, define_singer and get_line(line_number). The define_singer method prints a sentence stating the singer of the song. The get_line method takes a line_number as a parameter and prints the line number and the lyric at that line. Since arrays start at 0 but line numbers start at 1, we need to get the lyrics at the index of line_number – 1.
I also used attr_reader so that the instance variables of lyrics and singer can be read.
I create a new Song object and give it lyrics and a singer. I then call the define_singer() method on the bull_on_parade Song object. I use the get_line method to get line number 2. Finally, I print the lyrics to the screen by reading the lyrics variable of bulls_on_parade.
4. Search online for “object-oriented programming” and try to overflow your brain with what you read. Don’t worry if it makes absolutely no sense to you. Half of that stuff makes no sense to me too.
I like this explanation by the Bastard’s Book of Ruby.
This exercise was much less overwhelming than Exercise 39! This exercise introduces Classes, which are blueprints for creating new mini-modules. When you instantiate (create) a new object from a Class, you are creating a new mini-module and requiring it at the same time. The resulting mini-module is an object, which we can assign to a variable to work with. The attr_reader let’s us read the variable. This is the same as creating a method as below:
If we want to write the variable, we have to create a write method:
@lyrics = array
Instead of having to write these methods, we can use attr_reader :lyrics and attr_writer :lyrics. If we want both functionalities, we can simply say attr_accessor :lyrics ! Although the Codecademy Ruby track glanced over attr_reader/attr_writer, I feel like I have a better understanding through this exercise.