What does two dots in a row means in ruby?


#1



(2..num/2)


#2

It means range.

(2..10)

would be all the integers in the range 2 to 10, including 10.

(2...10)

would be all the integers in the range 2 to 10, excluding 10.


#3

Thanks, so if I say,

def prime? (num)
if num <= 1
false
elsif num == 2
true
else (2..num/2).none? do |i|
num % i == 0
end
end
end

what does num & i stands for here?


#4

num is the formal parameter of the method, as it appears.

puts prime?(19)

Inside the method, num will be 19.

Could you please post a link to this lesson so we can follow up?


#5

Thanks a lot!

What will i be in that case?

Sorry, I was just trying to find a way to detect prime number and came across this method online.

But I really appreciate your help!


#6

Sorry, forgot to cover that variable.

i is known as a block parameter and functions like a local variable of a method. i will be the iterator, starting at 2 and progressing up to num / 2. In the above example, (19), the range will be,

 2, 3, 4, 5, 6, 7, 8, 9

#7

No need to be sorry,

**So, basically function will try to divide given no by all the all the elements in range to find the prime no, **

**if It can't divide, it's a prime so, it gives true. **

and if it can divide, It's not a prime. So, it gives false, correct?


#8

It won't find the prime as much as determine primeness if there are no factors found.

19 % 2
 ...
19 % 9

None of these trials will net 0. So the loop will finish and 19 will fall out the bottom.

Not necessary. The loop will not run when num is 2.

Inside the loop,

def prime?(num)
    if num < 2
        return false
    (2..num/2).none? do |i|
        if num % i == 0
            return false
        end
    end
    return true
end

I'm winging here, until I see the lesson. Please post the URL to the exercise. Thanks.


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.