Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL
Help

Chapter 4 - Introduction to Ruby > Building Classes with Ruby - Pg. 112

112 CHAPTER 4 Introduction to Ruby if ARGV.size <= 0 || ARGV.size > 2 print "Usage: #{$0} Host [Port]\n" exit end server, mods = getHeader(ARGV[0],ARGV[1]) print "Server #{server} (#{mods})\n" BUILDING CLASSES WITH RUBY Classes allow us to group data with methods that can help manipulate, augment, and report that data. In Ruby, classes can build upon each other; they are designed to be extended and augmented to create custom classes for specific purposes. This allows us to build a basic socket server class and extend it to make different protocols work. We can leverage the base code from the socket server and write smaller amounts of code for each protocol. By doing this, when we find a bug in the base class, we don't have to copy and paste to propagate code throughout to define individual protocols. Let's take the header function that we created in Chapter 2, and turn it into a class. Building a class We define a class with the class keyword. Once we have defined and named our class, we must decide if we need an initialize method. The initialize method handles options passed to the class upon creation. It also handles any other setup that may be required when the class is created. Initialize is called automatically when we use our new operator, so we won't call it directly. If no setup is required, we can let Ruby handle it for us. The initialize function will be included automatically and will use the Ruby default, so we don't have to duplicate that code. Let's create an initialize method which will take the two options we passed into our getHeader function. #!/usr/bin/ruby require 'net/http' class MyHead def initialize(host,port = nil) @host = host @port = port.to_i || 80 end We have created a new class called MyHead , and in our initialize method we have listed our two options: host and port . We have assigned these to @host and @port . The @ sign designates these variables as instance variables. This allows us to