What are the reserved words BEGIN or END used for in Ruby?

后端 未结 6 1816
失恋的感觉
失恋的感觉 2021-02-01 18:30

This is a very hard to find word because in most cases they are not sensitive during a search. The best I could find outside of documentation is a test in IRB.

          


        
6条回答
  •  一个人的身影
    2021-02-01 18:48

    From The Ruby Programming Language:


    BEGIN and END Blocks

    Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks).

    BEGIN {
      # begin code
    } 
    END {
      # end code
    }
    

    A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order.


    So:

    $ cat beginend.rb
    END { puts :end }
    BEGIN { puts :begin }
    END { puts :end2 }
    BEGIN { puts :begin2 }
    
    puts :run
    $ ruby beginend.rb 
    begin
    begin2
    run
    end2
    end
    

提交回复
热议问题