Extending Core Ruby Classes

Ruby on Rails Tutorial

Unearth the potential of extending core Ruby classes with our insightful tutorial. Get a detailed understanding of how to add new methods to classes, with clear examples using the String and Array classes.

Key Insights

  • This tutorial teaches how to extend the string class by adding a new method.
  • It provides an exercise that shows how additional information can be added to a given class by opening a class declaration and inserting a new method.
  • It explains the power of Ruby, where this method can apply not only to our own classes, but also to the classes that come with Ruby or Rails.
  • The tutorial demonstrates how to add a new method to a core Ruby class, using the String class as an example.
  • It informs that Rails extends many core Ruby classes and adds a bunch of functionality to them, which is a common and potent technique in professional Rails development.
  • Lastly, it provides another example by extending the Array class and adding a method to it.

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.

Add a Custom Method to the String Class

  1. Open IRB

    Type 'irb' in Terminal to start Interactive Ruby.

  2. Reopen the String Class

    class String; def reverse_caps; self.reverse.upcase; end; end

  3. Use 'self' to Reference the Instance

    Inside the method, self is the current string value.

  4. Call Your New Method

    s = "Just a string"; s.reverse_caps returns GNIRTS A TSUJ.

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
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

    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 many 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

    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.

Learn more in these courses

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