Re:Ruby One-Liners
by faitswulff on Friday September 13, 2019 @11:16PM
(#20968724)
What is that BEGIN{...} and END{...} syntax? I've seen a good amount of Ruby, but haven't encountered that yet.
[ Parent
| on HN ]
It'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.
It'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.