Forum: Ruby Nested IF statements

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Angelo (Guest)
on 2006-05-12 02:05
I'm very new to Ruby and am desperately trying to figure out what seems
to be a fairly simple script.  Is there something special I need to know
in regards to IF statements with Ruby that may differ from most other
languages?

The structure of the script looks like the following:

for

    if

        if

        else

        end

    elsif

    end

    if

    end

end

It's bugging at the first and only elsif. (syntax error, unexpected
kELSIF, expecting kEND)
pat eyler (Guest)
on 2006-05-12 02:20
(Received via mailing list)
On 5/11/06, Angelo <removed_email_address@domain.invalid> wrote:
>
>         if
>
>         else
>
>         end
>
>     elsif

you need an else here
Jacob F. (Guest)
on 2006-05-12 19:33
(Received via mailing list)
On 5/11/06, Angelo <removed_email_address@domain.invalid> wrote:
>
>     if
>
>     end
>
> end
>
> It's bugging at the first and only elsif. (syntax error, unexpected
> kELSIF, expecting kEND)

I'm guessing it's actually a problem with your elided (not shown)
code. If I take you structure and add in some simple conditions and
statements, it runs fine:

  for i in (1..10).to_a
    if i > 5
      if i < 8
        puts "i is 6 or 7"
      else
        puts "i is 8, 9 or 19"
      end
    elsif i < 2
      puts "i is 1"
    end
    if (i % 2).zero?
      puts "#{i} is even"
    end
  end

produces:

  i is 1
  2 is even
  4 is even
  i is 6 or 7
  6 is even
  i is 6 or 7
  i is 8, 9 or 19
  8 is even
  i is 8, 9 or 19
  i is 8, 9 or 19
  10 is even

My guess is you have some other construct requiring an 'end' (while
loop, block, etc.) that is missing its 'end' between the first 'end'
(of the nested if) and the 'elsif' in question. Since you're still in
the other construct, the parser is expecting to see that construct
closed (with a kEND token) before seeing the kELSIF token of the
enclosing if statement.

Jacob F.
This topic is locked and can not be replied to.