tags:

views:

57

answers:

2

Hi guys. I have a little question about how ruby interprets de ensure clause in the code. As i know, ensure clause must always be enclosed by begin and end tokens.

For example, if i write this piece of code a kENSURE error will be raised (C:/Documents and Settings/jlomonaco/Desktop/borrar.rb:3: syntax error, unexpecte d kENSURE, expecting $end)

x=5
raise "ERROR!!!" if x==5
ensure
puts "some code has been executed"

However if I wrap this code between begin and end clauses no error will be raised:

begin
x=5
raise "ERROR!!!" if x==5
ensure
puts "some code has been executed"
end

So here comes my question:

I have discovered that inside a function definition isn't obligatory to wrap the ensure token between begin and end; for example i could just write this code and no errors will be raised:

def stackoverflow
 x=5
 raise "ERROR!!!" if x==5
ensure
 puts "some code has been executed"
end

stackoverflow

And if i write the begin and end tokens the code works well too. So where is it obligatory to put the BEGIN and END clauses?

Thanks!

+2  A: 

Based on a little experimentation, ensure seems to be valid in begin, def, class, and module blocks (i.e. definitions + begin), but not at the top level and not in loops, conditionals, or do blocks / { |args| ... }.

wdebeaum
Yes i think my question is very subtle and the answer is on experimentation as u said! Thanks for that information!
juanmaflyer
Good answers need facts and not speculation.
johannes
The results of experiments are facts. But I see your point; it's usually better to reference documentation (like Mark Westling does) than poke around with the interpreter, so I'll vote up Mark's answer.
wdebeaum
Of course, i prefer a book reference rather than an answer based on expermintation; but as this question was too specific i doubt that it has a 'book' answer. Anyway your expermientations and conclusions were correct wdebeam, thanks a lot again :)
juanmaflyer
+4  A: 

This behavior is documented in The Ruby Programming Language:

Throughout this discussion of exception handling, we have described the rescue, else, and ensure keywords as clauses of a begin statement. In fact, they can also be used as clauses of the def statement (defines a method), the class statement (defines a class), and the module statement (defines a module). Method definitions are covered in Chapter 6; class and module definitions are covered in Chapter 7.

I've found this to be a great reference book.

Mark Westling