News for hackers. Stuff that matters.
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.
Re:Ruby One-Liners by jhbadger on Friday September 13, 2019 @11:33PM (#20968767)
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.
Re:Ruby One-Liners by masklinn on Saturday September 14, 2019 @07:34AM (#20970155)
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.

Re:Ruby One-Liners by emmelaich on Saturday September 14, 2019 @03:22AM (#20969408)
What 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