Apply Today to our Front End or Back End Programs & check out our scholarships!

Go Back

Ruby Methods

Depending on the data type, we can use some built-in Ruby methods to manipulate the data!

Goals

  • Use developer skills to make sense of what unfamiliar code is doing
  • Understand and describe the purpose of methods
  • Apply new understanding of methods to short coding challenges

String Methods

In the spirit of exploring to learn, take a look at the code below. What do you think will happen when you run it?

first_name = "osCAr"
puts "Hello, #{first_name}!"
puts "Hello, #{first_name.capitalize}!"

Try It: Exploring String Methods

Read the code above and predict what will happen when you run it. Try to explain why.

Now, type or copy and paste the code into your replit and run it. Was your prediction correct?

Then, change capitalize to upcase, then downcase, then reverse. Re-run the code each time to change it, and observe the output.

Takeaways

  • Ruby provides a variety of methods that can be used specifically on Strings - we can think of them as actions.
  • A Ruby developer doesn't need to memorize every method that is available; some will be used regularly but others won't. For this reason, developers rely heavily on resources like ruby-doc.org!

The rand() Method

There are some methods that can be used for a specific purpose without having data to manipulate. The rand() method returns a random integer. When the rand() method is called with no arguments, it returns a decimal value greater than or equal to 0 and less than 1.

random_value = rand()
puts random_value
# => 0.7893798326241

To get a random integer, you can pass in an integer as an argument, between the parenthesis. The rand() method returns an integer value that is greater than or equal to 0 and less than the integer passed in.

random_value = rand(6)
puts random_value
# => 5

You can also pass in a range for the rand() method. To use an inclusive range, use two dots. For a non-inclusive range, use three dots. The following example shows how to use an inclusive range as the argument with a lower limit of 1 up to (and including) the upper limit of 20.

random_value = rand(1..20)
puts random_value
# => 20

The next example shows how to use a non-inclusive range as the argument, with a lower limit of 5 up to (but not including) the upper limit of 10.

random_value = rand(5...10)
puts random_value
# => 9

Try It: Using the rand() Method

Back in your sandbox replit, solve each of the challenges below.

  1. Store a random number between 1 and 99, inclusive of 99, in a variable called random_num. Use puts or print and run your code a few times to verify the result.
  2. Create a variable named lottery_number assigned to a random six-digit number.

Up Next