2 ms·
What is that BEGIN{...} and END{...} syntax? I've seen a good amount of Ruby, but haven't encountered that yet.
by faitswulff 7y ago
What is that BEGIN{...} and END{...} syntax? I've seen a good amount of Ruby, but haven't encountered that yet.
- jhbadger 7y agoIt's basically there to make Ruby an equivalent to AWK. It only makes sense if you are looping over the lines with -n. The BEGIN block runs at the start of the run, and the END block at the end. They are useful for things like initializing a sum variable to zero at the start and printing it out at the end.
- emmelaich 7y agoWhat really baked my noodle is that there is another "end" called __END__ used like this $ cat data.rb DATA.each_line { |ln|puts ln } __END__ fish cat dog $ ruby data.rb fish cat dog
- masklinn 7y agoIt's from awk: the BEGIN and END patterns match the start and end of a file/stream being processed, while normal patterns are checked on each line (and no pattern matches every line). This is very useful to script a setup -> for reach line -> summary of a file e.g. initialise a map in BEGIN, fill the map for each line, and print the map in END.