runpaint / read-ruby

Free ebook about Ruby 1.9
http://ruby.runpaint.org/
148 stars 28 forks source link

BEGIN and END outside of top level #131

Closed telemachus closed 9 years ago

telemachus commented 11 years ago

It might be worth documenting how BEGIN/END outside of the top level of code works (or doesn't work) in different Rubies:

# Ruby 1.8.7: this executes the puts unconditionally
if false
  BEGIN {  puts "Up is down, good is bad!"  }
end

# Ruby 1.9.3: the same code is a syntax error, but the error doesn't really
# make clear _why_ it's an error. Here's the error message:
unconditional.rb:2: syntax error, unexpected keyword_BEGIN
  BEGIN { puts "Up is down, good is bad!" }
       ^
unconditional.rb:2: syntax error, unexpected '}', expecting keyword_end

# Ruby 2.0.0: same code errors out with a clear error message:
unconditional.rb:2: BEGIN is permitted only at toplevel
BEGIN { puts "Up is down, good is bad!" }
     ^
kaleemullah360 commented 9 years ago

you are using BEGIN in function body. and error says it can be used out of function body. BEGIN can only be used at file scope.

telemachus commented 9 years ago

@kaleemullah360 I'm not sure I follow what you're saying. My point was that in different versions of Ruby the rules for BEGIN are different.

kaleemullah360 commented 9 years ago

in older version of ruby it doesn't show such error now it does in ruby > v2 and also tested this problem. when I put BEGIN inside function body it throws exception and when I put it out of function body it works fine. http://whitequark.org/blog/2013/04/14/unmentioned-features-of-ruby-2-dot-0/

telemachus commented 9 years ago

in older version of ruby it doesn't show such error now it does in ruby > v2

Yes. I know. That's what I was saying. I wasn't asking about the differences, and I wasn't confused why there was an error.

I just thought this guide should mention the variation in how BEGIN and END work for different versions of Ruby. But it no longer matters since this guide is gone (the whole website is gone).

Thanks.