Learn the fundamentals of Ruby on Rails through this comprehensive tutorial that covers essential concepts such as object-oriented programming, defining a class, and creating methods.
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:
Everything in Ruby is an object, Defining a class
Exercise Overview
Ruby is a programming language, and Ruby on Rails is a framework that utilizes Ruby. If you don’t take the time to learn Ruby syntax, you may struggle with Rails.
For the next series of exercises, we’re going to step away from Rails and websites. Instead we will start to play with and learn about the Ruby language, which is the foundation of Rails. You’ll learn important foundational Ruby concepts like classes, methods, properties, etc. which you will need to know later, when we get deeper into Rails development.
Everything in Ruby Is an Object
Fundamentally, Ruby is an object-based language. An object is a block of code that contains both variables and methods. At heart, object-oriented programming is simply meant to model the real world. Instead of being adrift in a sea of functions and arrays, objects are meant to make your code more readable and more powerful. We will emphasize real-world connections in this exercise by trying to build an object (a cat, in this case) from the inside out.
Open Terminal.
-
Here we can use Interactive Ruby, which is a great place to test out some of the basics of the Ruby programming language. Type the following to start up Interactive Ruby and then press Return. (You must always type Return after each line of code in Terminal. We won’t remind you again.)
irb
NOTE: The numbers in Terminal’s command prompt (like
2.6.3 :001
) are the version of Ruby (2.6.3) followed by the line of code you’re currently on. -
We’ll explore object-oriented programming by creating a virtual model of a cat. Where do we start with modeling our cat? Well, a cat has to meow, so type the following bold code:
puts "Meow!"
After you type this, Terminal will then “reply” by printing
Meow!
and on the next line printing the wordnil
. Interactive Ruby (IRB) will always print the return value of every statement you enter. The absence of any value is alwaysnil
. In this case, Terminal printsnil
because you typedputs
, which has no return value. -
That
nil
is rather unsightly, and we can avoid it by simply typing:"Meow!"
Terminal prints
"Meow!"
since the return value of a string (a series of characters) is nothing more than the string itself. This might be easier to understand if we make IRB do a little more work. -
Let’s have Terminal concatenate (join) two strings together. We can do this with the plus (+) character as if we were adding them, by typing the following. Pay close attention to where spaces are, they make a difference! If there’s a space inside quotes (like after Meow!) it will be remembered for later use.
"Meow! " + "I am hungry"
Terminal will show the return value of the combined (or concatenated) strings by adding them together to form one phrase surrounded by quotation marks:
“Meow! I am hungry” -
We just used the plus sign to combine two text strings. When used with numbers, the plus sign has a different function. Type the following:
2 + 3
As expected, Terminal will print the return value of 5.
-
If you add quotes around numbers, they will no longer be thought of as numbers, but as text strings. Try entering:
"2" + "3"
Terminal will show a return value of
"23"
, because we have concatenated the string “2” and then the string “3”.
Defining a Method
-
A method is a block of code that can be called over and over again. As you create a method by typing the code shown below, don’t worry about typing in the indention spaces at the start of lines—Terminal will indent them for you when you hit Return!
def say_meow "Meow!" end
-
We defined a simple method with three lines of code. Put it to work by typing:
say_meow
Now every single time we call
say_meow
IRB will print out"Meow!"
. Try callingsay_meow
as many times as you like. (TIP: Hitting the Up Arrow in Terminal will bring up the previously typed command.)Let’s break down the method we just defined:
-
def
stands for definition, indicating that we are about to define/create a new method. It always precedes the name of the method. -
say_meow
is the name of the method. -
"Meow!"
is the body of the method, the code that we want to execute when the method is called. -
end
signifies that the method is done.
NOTE: If you make mistakes typing in Terminal, and don’t catch the errors until after you press Return, you can cancel the current command by hitting Control–C (note that it’s Control, not Command!). As you get into larger blocks of commands that are multiple lines, you may need to hit Control–C several times.
-
Defining a Class
-
The picture remains incomplete: we have defined the method
say_meow
, but we have no object that can say “Meow!” yet. To do this, we have to define a class. Do so by typing the following:class Cat def say_meow "Meow!" end end
NOTE: You must type
end
twice. This might look like a typo, but it’s not; you’ll often find yourself typingend
twice when using IRB in Terminal. The firstend
is for thesay_meow
method and the second is for the Cat class.You have just created a simple class called Cat! Within that class, you have embedded a method (the
say_meow
method). The class definition looks a great deal like the method definition, except the first word isclass
and the first letter of the class name is capitalized. -
Let’s attempt to make our cat say meow by typing:
Cat.say_meow
-
Oh no! Notice that Terminal returns an error message. What went wrong?
Well, with our class definition, we’ve created the idea of a cat, but not a particular cat. A class is a template for making objects. Right now you have a blueprint for a cat, but no actual cats. (If you’re familiar with Plato’s concept of Forms, we’ve created the Platonic ideal of a cat.) To get our cat talking, we have to instantiate it; we have to create an actual cat. Let’s do that now.
-
Let’s create an instance of the Cat class and try to make it speak by typing:
fluffy = Cat.new fluffy.say_meow
Excellent! We have created an instance of the Cat class. This is also called an object. The Terminal now returns
"Meow!"
just as we hoped it would.Let’s break down those last two lines of code:
-
fluffy = Cat.new
is where the real magic happens. In this one simple line, we have created a new instance of the Cat class and assigned it to thefluffy
variable. Amazing, we have created a cat out of thin air! Now that we have created a cat named fluffy, it can do all of the things that our template of a cat (the Cat class) defined, such as say “meow”. -
fluffy.say_meow
introduces a period between the variable and the method. LikeCat.new
, this uses a dot syntax where the period separates the object/class and the method you are calling.
-
Let’s take a moment to demystify a bit of IRB’s back-chat. Look back a few lines and notice that when we created fluffy by typing
fluffy = Cat.new
, Terminal returned a string of gibberish that looked something like this#<Cat:0x007f8ebaleef88>
. This is the class nameCat
followed by a unique identifier, and it is the default return value for a new object created in Ruby.-
What would happen if we created a different cat? Type the following:
george = Cat.new george.say_meow
Terminal returns
"Meow!"
so we know that our new cat, george, behaves just like fluffy. Notice that after the line where you typedgeorge = Cat.new
, his unique identifier is the same length as fluffy’s but has a slightly different value, something like#<Cat:0x007f8eb904ceb0>
. These unique identifiers confirm that fluffy and george are not the same cat, although both of them can indeed say “Meow!” because they are instances of the same Cat class. In the next exercise you’ll continue with the Cat class and objects, so leave the Terminal open.