Home > Articles > Programming > Ruby

Rails-Flavored Ruby

This chapter is from the book

4.4 Ruby Classes

We've said before that everything in Ruby is an object, and in this section we'll finally get to define some of our own. Ruby, like many object-oriented languages, uses classes to organize methods; these classes are then instantiated to create objects. If you're new to object-oriented programming, this may sound like gibberish, so let's look at some concrete examples.

4.4.1 Constructors

We've seen lots of examples of using classes to instantiate objects, but we have yet to do so explicitly. For example, we instantiated a string using the double quote characters, which is a literal constructor for strings:

>> s = "foobar"      # A literal constructor for strings using double quotes
=> "foobar"
>> s.class
=> String

We see here that strings respond to the method class , and simply return the class they belong to.

Instead of using a literal constructor, we can use the equivalent named constructor, which involves calling the new method on the class name:

>> s = String.new("foobar")   # A named constructor for a string
=> "foobar"
>> s.class
=> String
>> s == "foobar"
=> true

This is equivalent to the literal constructor, but it's more explicit about what we're doing.

Arrays work the same way as strings:

>> a = Array.new([1, 3, 2])
=> [1, 3, 2]

Hashes, in contrast, are different. While the array constructor Array.new takes an initial value for the array, Hash.new takes a default value for the hash, which is the value of the hash for a nonexistent key:

>> h = Hash.new
=> {}
>> h[:foo]            # Try to access the value for the nonexistent key :foo.
=> nil
>> h = Hash.new(0)    # Arrange for nonexistent keys to return 0 instead of nil.
=> {}
>> h[:foo]
=> 0

4.4.2 Class Inheritance

When learning about classes, it's useful to find out the class hierarchy using the super-class method:

>> s = String.new("foobar")
=> "foobar"
>> s.class                        # Find the class of s.
=> String
>> s.class.superclass             # Find the superclass of String.
=> Object
>> s.class.superclass.superclass  # Find the superclass of Object (it's nil!).
=> nil

A diagram of this inheritance hierarchy appears in Figure 4.2. We see here that the superclass of String is Object , but Object has no superclass. This pattern is true of every Ruby object: Trace back the class hierarchy far enough and every class in Ruby ultimately inherits from Object , which has no superclass itself. This is the technical meaning of "everything in Ruby is an object."

Figure 4.2

Figure 4.2 The inheritance hierarchy for the String class.

To understand classes a little more deeply, there's no substitute for making one of our own. Let's make a Word class with a palindrome? method that returns true if the word is the same spelled forward and backward:

>> class Word
>>   def palindrome?(string)
>>     string == string.reverse
>>   end
>> end
=> nil

We can use it as follows:

>> w = Word.new             # Make a new Word object
=> #<Word:0x22d0b20>
>> w.palindrome?("foobar")
=> false
>> w.palindrome?("level")
=> true

If this example strikes you as a bit contrived, good; this is by design. It's odd to create a new class just to create a method that takes a string as an argument. Since a word is a string, it's more natural to have our Word class inherit from String, as seen in Listing 4.7. (You should exit the console and re-enter it to clear out the old definition of Word.)

Listing 4.7. Defining a Word class in irb

>> class Word < String             # Word inherits from String.
>>   # Return true if the string is its own reverse.
>>   def palindrome?
>>     self == self.reverse        # self is the string itself.
>>   end
>> end
=> nil

Here Word < String is the Ruby syntax for inheritance (discussed briefly in Section 3.1.2), which ensures that, in addition to the new palindrome? method, words also have all the same methods as strings:

>> s = Word.new("level")   # Make a new Word, initialized with "level".
=> "level"
>> s.palindrome?           # Words have the palindrome? method.
=> true
>> s.length                # Words also inherit all the normal string methods.
=> 5

Since the Word class inherits from String , we can use the console to see the class hierarchy explicitly:

>> s.class
=> Word
>> s.class.superclass
=> String
>> s.class.superclass.superclass
=> Object

This hierarchy is illustrated in Figure 4.3.

Figure 4.3

Figure 4.3 The inheritance hierarchy for the (non-built-in) Word class from Listing 4.7.

In Listing 4.7, note that checking that the word is its own reverse involves accessing the word inside the Word class. Ruby allows us to do this using the self keyword: Inside the Word class, self is the object itself, which means we can use

self == self.reverse

to check if the word is a palindrome.14

4.4.3 Modifying Built-In Classes

While inheritance is a powerful idea, in the case of palindromes it might be even more natural to add the palindrome? method to the String class itself, so that (among other things) we can call palindrome? on a string literal, which we currently can't do:

>> "level".palindrome?
NoMethodError: undefined method 'palindrome?' for "level":String

Somewhat amazingly, Ruby lets you do just this; Ruby classes can be opened and modified, allowing ordinary mortals such as ourselves to add methods to them:15

>> class String
>>   # Return true if the string is its own reverse.
>>   def palindrome?
>>     self == self.reverse
>>   end
>> end
=> nil
>> "deified".palindrome?
=> true

(I don't know which is cooler: that Ruby lets you add methods to built-in classes, or that "deified" is a palindrome.)

Modifying built-in classes is a powerful technique, but with great power comes great responsibility, and it's considered bad form to add methods to built-in classes without having a really good reason for doing so. Rails does have some good reasons; for example, in web applications we often want to prevent variables from being blank—e.g., a user's name should be something other than spaces and other whitespace—so Rails adds a blank? method to Ruby. Since the Rails console automatically includes the Rails extensions, we can see an example here (this won't work in plain irb ):

>> "".blank?
=> true
>> "      ".empty?
=> false
>> "      ".blank?
=> true
>> nil.blank?
=> true

We see that a string of spaces is not empty, but it is blank. Note also that nil is blank; since nil isn't a string, this is a hint that Rails actually adds blank? to String 's base class, which (as we saw at the beginning of this section) is Object itself. We'll see some other examples of Rails additions to Ruby classes in Section 9.3.3.

4.4.4 A Controller Class

All this talk about classes and inheritance may have triggered a flash of recognition, because we have seen both before, in the Pages controller (Listing 3.16):

class PagesController < ApplicationController

  def home
    @title = "Home"
end
def contact
    @title = "Contact"
  end
def about
    @title = "About"
  end
end

You're now in a position to appreciate, at least vaguely, what this code means: PagesController is a class that inherits from ApplicationController, and comes equipped with home, contact, and about methods, each of which defines the instance variable @title. Since each Rails console session loads the local Rails environment, we can even create a controller explicitly and examine its class hierarchy:16

>> controller = PagesController.new
=> #<PagesController:0x22855d0>
>> controller.class
=> PagesController
>> controller.class.superclass
=> ApplicationController
>> controller.class.superclass.superclass
=> ActionController::Base
>> controller.class.superclass.superclass.superclass
=> Object

A diagram of this hierarchy appears in Figure 4.4.

Figure 4.4

Figure 4.4 The inheritance hierarchy for the Pages controller.

We can even call the controller actions inside the console, which are just methods:

>> controller.home
=> "Home"

This return value of "Home" comes from the assignment @title = "Home" in the home action.

But wait—actions don't have return values, at least not ones that matter. The point of the home action, as we saw in Chapter 3, is to render a web page. And I sure don't remember ever calling PagesController.new anywhere. What's going on?

What's going on is that Rails is written in Ruby, but Rails isn't Ruby. Some Rails classes are used like ordinary Ruby objects, but some are just grist for Rails' magic mill. Rails is sui generis, and should be studied and understood separately from Ruby. This is why, if your principal programming interest is writing web applications, I recommend learning Rails first, then learning Ruby, then looping back to Rails.

 

4.4.5 A User Class

We end our tour of Ruby with a complete class of our own, a User class that anticipates the User model coming up in Chapter 6.

So far we've entered class definitions at the console, but this quickly becomes tiresome; instead, create the file example_user.rb in your Rails root directory and fill it with the contents of Listing 4.8. (Recall from Section 1.1.3 that the Rails root is the root of your application directory; for example, the Rails root for my sample application is /Users/mhartl/rails_projects/sample_app.)

Listing 4.8. Code for an example user.

example_user.rb

class User
  attr_accessor :name, :email

  def initialize(attributes = {})
    @name  = attributes[:name]
    @email = attributes[:email]
  end

  def formatted_email
    "#{@name} <#{@email}>"
  end
end

There's quite a bit going on here, so let's take it step by step. The first line,

attr_accessor :name, :email

creates attribute accessors corresponding to a user's name and email address. This creates "getter" and "setter" methods that allow us to retrieve (get) and assign (set) @name and @email instance variables.

The first method, initialize, is special in Ruby: It's the method called when we execute User.new. This particular initialize takes one argument, attributes:

def initialize(attributes = {})
  @name  = attributes[:name]
  @email = attributes[:email]
end

Here the attributes variable has a default value equal to the empty hash, so that we can define a user with no name or email address (recall from Section 4.3.3 that hashes return nil for nonexistent keys, so attributes[:name] will be nil if there is no :name key, and similarly for attributes[:email] ).

Finally, our class defines a method called formatted_email that uses the values of the assigned @name and @email variables to build up a nicely formatted version of the user's email address using string interpolation (Section 4.2.2):

def formatted_email
  "#{@name} <#{@email}>"
end

Let's fire up the console, require the example user code, and take our User class out for a spin:

>> require 'example_user'       # This is how you load the example_user code.
=> ["User"]
>> example = User.new
=> #<User:0x224ceec @email=nil, @name=nil>
>> example.name                 # nil since attributes[:name] is nil
=> nil
>> example.name = "Example User"           # Assign a non-nil name
=> "Example User"
>> example.email = "user@example.com"      # and a non-nil email address
=> "user@example.com"
>> example.formatted_email
=> "Example User <user@example.com>"

This code creates an empty example user and then fills in the name and email address by assigning directly to the corresponding attributes (assignments made possible by the attr_accessor line in Listing 4.8). When we write

example.name = "Example User"

Ruby is setting the @name variable to "Example User" (and similarly for the email attribute), which we then use in the formatted_email method.

Recalling from Section 4.3.4 that we can omit the curly braces for final hash arguments, we can create another user by passing a hash to the initialize method to create a user with pre-defined attributes:

>> user = User.new(:name => "Michael Hartl", :email => "mhartl@example.com")
=> #<User:0x225167c @email="mhartl@example.com", @name="Michael Hartl">
>> user.formatted_email
=> "Michael Hartl <mhartl@example.com>"

We will see starting in Chapter 8 that initializing objects using a hash argument is common in Rails applications.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020