user507220
user507220

Reputation:

if..else if inside a do..end block in Ruby

I wrote a program which had if...else if inside a do..end block in Ruby. Something like this:

[1..100].each do |num|
    if num % 3 == 0 and num % 5 == 0 
        tf += 1
    else if num % 3 == 0 and num % 5 != 0 
        t += 1
    end
    end
end

My question is: why is it necessary to put three ends at the end? From what is shown in the Ruby Wikibook, the if..else if requires only one end and the do..end requires only one end too.

Upvotes: 2

Views: 6645

Answers (3)

sepp2k
sepp2k

Reputation: 370102

You only need one end to close an if block (even if that if block contains multiple elsifs like in the wikibook). However in your code there are two if blocks: one outside and another one in the else part of the outer if block.

Long story short: if you use elsif instead of else if, you only need one end to close the if.

Also note that [1..100].each will yield exactly once because [1..100] is an array with just one single element: the range object 1..100. You probably want (1..100).each instead.

Upvotes: 2

Maurício Linhares
Maurício Linhares

Reputation: 40313

Your code should be written like this:

[1..100].each do |num|
    if num % 3 == 0 and num % 5 == 0 
        tf += 1
    elsif num % 3 == 0 and num % 5 != 0 
        t += 1
    end
end

Here's how your code should have been written with an elsif and not an else if. The other end is to close the if at the else if.

Upvotes: 2

Benoit Garret
Benoit Garret

Reputation: 13675

The else if opens a new block. Use elsif to chain if and else clauses.

Upvotes: 6

Related Questions