开发者

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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜