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

后端 未结 6 2026
失恋的感觉
失恋的感觉 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:42

    the BEGIN/END is really handy when using the -e option to process a stream. For example, to total a file of numbers:

    cat < numbers
    1
    5 
    10
    20
    EOF
    
    cat numbers | ruby -ane 'BEGIN { $t=0}; END {puts $t}; $t += $_.to_i'
    

    note how the BEGIN zeros out the global, and the END prints the result.

提交回复
热议问题