Step 8: Methods


We learned before that computer programs are made up of two components: data, and procedures for modifying and moving that data. In Ruby, these procedures are called methods. Let’s learn about a few useful methods that we can use to work with the primitive data types we’ve already learned about. We know that "1" and 1 represent two different things in Ruby, but we also know as humans that the character "1" usually represents the concept of the number 1. Ruby is a smart language, and when we have values that seem like they could just as easily be different types, it allows us to change the type.

"13" + 7

If you run the code above in repl.it, you will get an error. This is the first time we’ve encountered an error, and in this case Ruby is telling us that we’re attempting to do something we’re not allowed to do: add a string and an integer together.

"13".to_i + 7 
# => 20

In the example above, we called the to_i method on the string "13", which converted it into an integer, allowing it to be added to the integer 7. In Ruby, all data are represented as objects. Objects have data, and methods to do things to that data. Above the string "13" is an object with data equivalent to that string, and a bunch of methods to do things to that string, one of which is to_i.

Let’s take a look at another example of a string method.

"destination dev".capitalize
# => "Destination Dev"

Here we called the string .capitalize method on our string, and predictably (given the name of the method) a capitalized version of the original string was returned. Methods are (almost) always called in Ruby using the syntax object.method_name.

Another useful method we can learn now is the method .puts. puts stands for "put string", and it will allow us to print output in our REPL before the entire program returns.

1 + 1
13 + 5
6 + 6

If you run the above code, it will just return the result of the final line, 6 + 6, as output. Using puts, we can get output from each line.

puts(1 + 1)
puts(13 + 5)
puts(6 + 6)

The code above now outputs the result of each line. As you can see, puts is an example of a method that doesn’t use the object.method_name syntax (if you’re curious why, ask during your interview). puts also gives us the first example of a method that accepts an argument. Arguments are values that you can pass into a method using the method_name(value) syntax, and the method can then do things with these values the same way it can do things with the object calling the method. In this case, puts prints the result of the expression.