user1972031
user1972031

Reputation: 557

catch/try block doesn't run in Ruby

I got a syntax error running the following snippet of Ruby code.

catch(:outer)
  m, n = 1,1
  loop do
    catch(:inner)
      for i in 3 .. 100
        m, n = (m*2), m
        throw :outer if m > 9_999
        throw :inner if m > 5_000
      end         # for-loop
    end          # catch(:inner)
  end # loop
end # catch(:outer)
#=> syntax error, unexpected keyword_end, expecting $end

It doesn't like the two end statements at the end. What is wrong with it?

Upvotes: 2

Views: 132

Answers (2)

Serjik
Serjik

Reputation: 10941

The correct syntax will be:

catch(:outer) do
  m, n = 1,1
  loop do
    catch(:inner) do
      for i in 3 .. 100
        m, n = (m*2), m
        throw :outer if m > 9_999
        throw :inner if m > 5_000
      end         # for-loop
    end          # catch(:inner)
  end # loop
end # catch(:outer)

ruby blocks match with do-end pair or {}, catch-end is not a ruby statement like for-end

Upvotes: 4

sawa
sawa

Reputation: 168131

You don't have a do after catch that matches the end. An end must match with do or a keyword (such as class, module, begin). The catch is a method, not a keyword.

Upvotes: 2

Related Questions