Lots of Other Methods

Learn how to look up lots of useful methods that we can use in our everyday Ruby code.

Names of methods reflect their behavior

If we look at the methods defined on strings, arrays, or hashes (run [].methods.sort or {}.methods.sort ), then we’ll find many method names that look like they’re doing exactly what their names describe.

For example, some of the things we can do with strings are:

  • "a string".capitalize returns "A string", with the first letter uppercase.

  • "a string".length returns 8, which is the length of the string.

  • "a string".start_with?("a") returns true because the string starts with an "a".

  • "a string".include?("s") returns true because the string contains the character "s".

Similarly, some examples for useful methods on arrays are:

  • [5, 1, 3].sort returns another array, with the elements sorted: [1, 3, 5].

  • [5, 1, 3].size returns 3, the number of elements in the array.

  • [1, 1, 1, 2].uniq returns a new array with duplicate elements removed: [1, 2].

  • [1, 2, 3].join(", ") returns a string, "1, 2, 3".

  • [1, 2, 3].include?(2) returns true because the array contains the number 2.

How do we find all these methods?

The quickest way to find a specific method for an object is to search for “ruby array sort.” That will point you to the Ruby documentation. Another way is to read through all the methods for the class on the respective Ruby documentation page. We can also read through the method names returned by [1, 2, 3].methods.sort.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy