Ruby Wizardry An Introduction to Programming for Kids

Ruby Wizardry An Introduction to Programming for Kids

Author:Eric Weinstein
Format: epub


Object-Oriented Programming

Finally, we learned that writing programs that revolve around classes and objects is called object-oriented programming (OOP). Our minstrel is a good example of an object: a piece of code that acts just like something in the real world! It has attributes (facts about itself) as well as behavior, which is just a way of talking about the methods the object knows how to use. We can define the behavior of any minstrel with a Minstrel class, as follows.

minstrel_review_3.rb

class Minstrel attr_reader :name @@number_of_minstrels = 0 def initialize(name) @name = name @@number_of_minstrels += 1 end def sing(song_name) puts "Time to sing a song called: #{song_name}!" puts 'Tralala!' end def self.number_of_minstrels @@number_of_minstrels end end

Our class has an attr_reader for :name (meaning we can read the name, but not change it), as well as a @@number_of_minstrels class variable that keeps track of how many instances we’ve created and an initialize method that gives our minstrel a name and increases the @@number_of_minstrels.

It also has two methods: one, sing, is a method of minstrel instances and sings a little song, and the other, self.number_of_minstrels, is a method of the Minstrel class and tells us how many minstrels we’ve created so far.

Let’s see them in action!

>> load 'minstrel_review_3.rb' => true >> wherefore = Minstrel.new('Wherefore') => #<Minstrel:0x000001031eac68 @name="Wherefore"> >> Minstrel.number_of_minstrels => 1 wherefore.sing('A Tail of Two Foxes') Time to sing a song called: A Tail of Two Foxes! Tralala! => nil

Voilà! We can create a new minstrel, call Minstrel.number_of_minstrels to see that we’ve created one, and then call our minstrel instance (wherefore)’s sing method to hear his ballad “A Tail of Two Foxes.”

Things are starting to get a bit suspenseful around here, so I’m gonna go grab a bag of popcorn—be right with you. In the meantime, go on ahead to see what the King, Scarlet, and Ruben find when they get back to the castle, and get ready for even more object-oriented Ruby magic!



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.