FAQ: Methods, Blocks, & Sorting - Why Methods?

This community-built FAQ covers the “Why Methods?” exercise from the lesson “Methods, Blocks, & Sorting”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Ruby

FAQs on the exercise Why Methods?

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

for i in 2…n-1
if n % i == 0
is_prime = false

please can someone be so kind to explain what is it?

In the example code, we’re checking whether n is an integer, and then whether it is a prime number or not. Prime numbers can only be divided by themselves and 1.

In the portion of the code you mentioned, i is the iterator in the for loop, which is checking one at a time whether n is divisible by a number between 2 and n-1.

n represents the integer we’re checking, and n-1 is one less than the integer.

For example, prime(11) results in a for loop that iterates from 2 to 10. Since 11 is not divisible by any of these numbers, n % i is never == 0; it is a prime number.

prime(51) results in a for loop that iterates from 2 to 50. Since 51 is divisible by some numbers in this range, it is not a prime number. This is checked with n % i == 0 For example, 51 % 3 == 0. So is_prime = false in the case of 51.

Thank you, Marilyn! It is much better now.

1 Like