Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Ruby .each iteration clarification

The questions asks: Write a method, is_prime?, that takes a number num and returns true if it is prime and false otherwise

'''ruby def is_prime?(num) (2...num).each do |d| return false if num % d == 0 end true end '''

My question is what is (2...num) process called? Also for example if i set is_prime?(2) what function does the placeholder |d| do?

thank you!

3 Answers

I think you just want to do:

def is_prime(num)
    if num #add your check here
        return true
    else
        return false
    end
end

I don't think there is a reason to iterate here. You want the method to take in only one number, hence the "num"

thanks for the reply brandon

So the first code that i had was:

def is_prime?(num) if num % 2 != 0 return true else return false end end

The problem I noticed with this code is that 2 will return a false statement when 2 is a prime number.

You could said that if

if num % 2 != 0 || num == 2

The only problem here is that being divisible by 2 is not the definition of prime. I see what you were doing originally. You were looking at all numbers from 2 to the number with 2..num, and if none of those actually divide into the number, then you are prime. You could actually change it to 2..(num -1 ) since we don't need to check num.

I would try

def is_prime(num)
  for d in 2..(num - 1)
   if (num % d) == 0
    return false
   end
  end

  true
 end