Key Concepts

Review core concepts you need to learn to master this subject

Ruby method

def greeting puts "Hello world!" end #In this example, the first line or header contains the keyword "def" and the method name. puts "Hello world!" is within the body of the method, which describes the certain task that the method carries out. It is also indented two spaces by convention. Following the body, the method ends with the end keyword.

A Ruby method is a reusable section of code written to execute a certain task. It is defined with the def keyword, followed by a method name, a method body, and ends with the end keyword:

Ruby Method Parameters & Arguments

def greeting puts "Hello world!" end #In this example, the first line or header contains the keyword "def" and the method name. puts "Hello world!" is within the body of the method, which describes the certain task that the method carries out. It is also indented two spaces by convention. Following the body, the method ends with the end keyword.

In Ruby, parameters are placeholders for real values or arguments passed into a method when it is called. When calling a method that requires parameters, arguments (ie. real values) must be passed in for those parameters.

Ruby Method Splat

def greeting puts "Hello world!" end #In this example, the first line or header contains the keyword "def" and the method name. puts "Hello world!" is within the body of the method, which describes the certain task that the method carries out. It is also indented two spaces by convention. Following the body, the method ends with the end keyword.

In a Ruby method, a splat (*) operator is used to indicate that a parameter can have an unknown number of arguments.

Ruby Return

def greeting puts "Hello world!" end #In this example, the first line or header contains the keyword "def" and the method name. puts "Hello world!" is within the body of the method, which describes the certain task that the method carries out. It is also indented two spaces by convention. Following the body, the method ends with the end keyword.

In Ruby, the return keyword is used to pass back a value from a method.

Ruby Block

def greeting puts "Hello world!" end #In this example, the first line or header contains the keyword "def" and the method name. puts "Hello world!" is within the body of the method, which describes the certain task that the method carries out. It is also indented two spaces by convention. Following the body, the method ends with the end keyword.

In Ruby, a block is a section of code defined within the keywords do and end or with curly braces {}. This is usually preceded by an integer followed by .times to indicate how many times the code is to be executed.

Ruby Block Parameter

def greeting puts "Hello world!" end #In this example, the first line or header contains the keyword "def" and the method name. puts "Hello world!" is within the body of the method, which describes the certain task that the method carries out. It is also indented two spaces by convention. Following the body, the method ends with the end keyword.

In Ruby, a method can take a block as a parameter.

Passing a block to a method is a great way of abstracting certain tasks from the method and defining those tasks when we call the method.

Ruby Sort Method

def greeting puts "Hello world!" end #In this example, the first line or header contains the keyword "def" and the method name. puts "Hello world!" is within the body of the method, which describes the certain task that the method carries out. It is also indented two spaces by convention. Following the body, the method ends with the end keyword.

In Ruby, the .sort array method is used to sort items in an array in ascending order (least to greatest).

Ruby Combined Comparison Operator

def greeting puts "Hello world!" end #In this example, the first line or header contains the keyword "def" and the method name. puts "Hello world!" is within the body of the method, which describes the certain task that the method carries out. It is also indented two spaces by convention. Following the body, the method ends with the end keyword.

In Ruby, the combined comparison operator, <=>, also known as the spaceship operator is used to compare two objects. It returns 0 if the first operand equals the second, 1 if the first operand is greater than the second, and -1 if the first operand is less than the second.

Arrow Chevron Left Icon
Methods, Blocks, & Sorting
Lesson 1 of 2
Arrow Chevron Right Icon
  1. 1
    A method is a reusable section of code written to perform a specific task in a program. You might be wondering why you need to separate your code into methods, rather than just writing everythi…
  2. 2
    Methods are defined using the keyword def (short for “define”). Methods have three parts: 1. The header, which includes the def keyword, the name of the method, and any arguments the method ta…
  3. 3
    Now it’s time for you to build your own method. Remember, the syntax looks like this: def method_name # Do something! end
  4. 4
    Defining a method is great, but it’s not much use to you unless you call it, or tell your program to execute it. For example, if you call a method called cartoon_fox, the program will start looki…
  5. 5
    If a method takes arguments, we say it accepts or expects those arguments. We might define a function, square, like so: def square(n) puts n ** 2 end and call it like this: square(12) # ==>…
  6. 6
    Speaking of not knowing what to expect: your methods not only don’t know what arguments they’re going to get ahead of time but occasionally, they don’t even know how many arguments there will be. …
  7. 7
    Sometimes we don’t just want a method to print something to the console, but we actually want that method to hand us (or another method!) back a value. For that, we use return. def double(n) ret…
  8. 8
    You won’t become a Master Method Maker ‘til you make a mess of methods. (Say that three times fast.) def by_five?(n) return n % 5 == 0 end The example above is just a reminder on how to defi…
  9. 9
    Most methods that you’ve worked with have defined names that either you or someone else gave them (i.e. [array].sort(), “string”.downcase(), and so on). You can think of blocks as a way of creati…
  10. 10
    There are some differences between blocks and methods, however. Check out the code in the editor. The capitalize method capitalizes a word, and we can continually invoke the capitalize method by n…
  11. 11
    A method can take a block as a parameter. That’s what .each has been doing this whole time: taking a block as a parameter and doing stuff with it! You just didn’t notice because we didn’t use the o…
  12. 12
    Sorting arrays is a very common problem in computer science, and is well studied for that reason. There are many algorithms —well-defined sequences of steps—each with its own trade-offs and advan…
  13. 13
    If we were to hand you five books and ask you to arrange them, sorted by title, on a shelf, how would you do it? Most sorting algorithms assume we are sorting an array of items, which involves com…
  14. 14
    We can also use a new operator called the combined comparison operator to compare two Ruby objects. The combined comparison operator looks like this: . It returns 0 if the first operand (item …
  15. 15
    What if we wanted to sort the books by title, but from Z – A, or descending order? It appears that Ruby’s sort method only works for A – Z, or ascending order. The sort method assumes by default …
  16. 16
    Let’s quickly review how to create a basic Ruby method. def double(n) return n * 2 end The example above is just a syntax reminder.
  17. 17
    Good! Now let’s make our method a bit more complex by adding arguments and a return statement. def double(n) return n * 2 end
  18. 18
    Let’s go over what we learned about blocks. numbers = [5, 2, 8] sum = 0 numbers.each do |n| sum += n end puts sum The example above is just a reminder about syntax. We calculate the sum of a l…
  19. 19
    Finally, let’s review what we learned about sorting. books.sort! do |firstBook, secondBook| firstBook secondBook end Remember that the above example was how we sorted in alphabetical order.
  1. 1
    We noticed in the last lesson that .sort! didn’t have a built-in way of handling sorting in reverse alphabetical order. Now that we know how to write our own Ruby methods, we can fix that!
  2. 2
    First, we’ll need to define our alphabetize method.
  3. 3
    Let’s start with the new bit of code you saw in exercise 1: def alphabetize(arr, rev=false) The first part makes sense—we’re defining a method, alphabetize. We can guess that the first parameter i…
  4. 4
    Great! Now let’s add a little logic to our method. numbers = [5, 1, 3, 8] numbers.sort! puts numbers 1. In the above example, we create a new array called numbers. 2. Then, we sort the array. 3….
  5. 5
    Great! Now we need to add the right logic to our method. numbers = [1, 2, 3, 4, 5] numbers.reverse! puts numbers 1. In the example above, we create an array called numbers. 2. Then, we reverse t…
  6. 6
    Well done! You now have your very own method that adds functionality that Ruby didn’t have before. Building your own methods is great for using code over and over without having to retype things, …