Extending Core Ruby Classes

Free Ruby on Rails Tutorial

Learn how to extend core Ruby classes and create new methods in this comprehensive Ruby on Rails tutorial.

This exercise is excerpted from Noble Desktop’s past web development training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Topics covered in this Ruby on Rails tutorial:

Extending the string class, Adding a new method to the string class

Exercise Overview

You may have noticed that at times, we have added additional information to a given class by simply opening a class declaration again for that class and inserting a new method inside.

Take a look at this example (but don’t type it):

class Cat
    end
class Cat
    def meow
      puts "Meow"
      end
    end
Full-Stack Web Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

The second class declaration did not override the first—it simply added a new method to it.

Part of the power of Ruby is that this can apply not only to our own classes, but also to the classes that come with Ruby or Rails. In this exercise, we’ll be looking at extending core Ruby classes.

Extending Core Ruby Classes

  1. If Interactive Ruby isn’t running, go to/open Terminal and type the irb command.

  2. Let’s start by using the String class and creating a new string for our example:

    s = "Just a string"
    
  3. If we take a quick look at its class by typing…

    s.class
    

    We see that it is of the String class.

  4. You should remember that in Ruby, there are a lot of built-in methods for strings. As a reminder, try typing a couple of methods:

    • s.reverse
    • s.reverse.upcase

    First you’ll see the string reverse, then the string is reversed and made uppercase.

Adding a New Method to a Core Ruby Class

So let’s say we know we are going to be doing these commands a lot. We can actually create a single, custom method to both reverse the string and upcase it all at once.

  1. We’ll start by adding our own method to the String class:

    class String
       def reverse_caps
          self.reverse.upcase
          end
       end
    

    NOTE: self will return the current value of the string itself.

  2. Now call the new method:

    s.reverse_caps
    

    Terminal should return the string reversed and in all caps: GNIRTS A TSUJ

    This is just a little example to show some of the power of Ruby. You can program it to do almost anything.

    Rails itself extends many core Ruby classes in different ways and adds a bunch of functionality to them that they didn’t already have. This is a very common and powerful technique. Likewise, a lot of gems extend core Rails components. This approach is pretty central to how professional Rails development works.

Extending Another Core Ruby Class

  1. Let’s try another example, this time using the Array class:

    a = [2, 4, 6]
    
  2. Type this to confirm that indeed it is of the Array class:

    a.class
    
  3. It’s time to add a method to the Array class:

    class Array
       def square_all
          self.collect(&:abs2)
          end
       end
    

    This method will square each component of the array. abs2 gives us the absolute value of an integer, squared. We used the & to send the abs2 method to collect which squares each element. This is like how we used the & to turn a proc into a block earlier.

  4. Call the method:

    a.square_all
    

    Terminal should return the square of each number: [4, 16, 36]

  5. Let’s take another look at the &:abs2 shorthand we used. We used an & to send the abs2 method to collect which squared each element in our array. To see it in action again, type the following:

    [2, 4, 6].map(&:abs2)
    
  6. This is the same as if we had written the following using a block. Type it into Terminal to see it returns the same result:

    [2, 4, 6].map { |i| i.abs2 }
    
  7. Even the above statement was a condensed version as we could have also used the send method as shown below. Type it into Terminal to see the same result:

    [2, 4, 6].map { |i| i.send(:abs2) }
    

    All these methods returned the same values, but as you can see, using the & lets us type less code.

  8. Feel free to leave IRB running to continue on to the next exercise.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram