Awk-like BEGIN and END with Ruby command line

One of the most interesting things in Ruby is the ability to behave like typical Unix command line tools to do things like (similar to the example in the official documentation):

$ echo "matz" | ruby -pe '$_.upcase!' MATZ 

Awk, on the other hand, can perform aggregation on lines from standard input, for example, by summing a sequence of numbers:

 $ for (( i=0; $i < 50; i++ )); do echo $i; done | awk 'BEGIN { tot=0; } { tot += $0 } END { print tot }' 1225 

I would like to know if it is possible to get Ruby to do what is achieved using the above Awk BEGIN and END blocks in order to be able to perform similar aggregation operations.

+1
source share
2 answers
 seq 49 | ruby -pe 'BEGIN { $tot=0 }; $tot += $_.to_i; END { print $tot }' 
+4
source

In fact, ruby ​​has BEGIN / END support. for example see this blog post: http://burkelibbey.posterous.com/rubys-other-begin

Additional documentation: http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html#UA

Hth

+1
source

Source: https://habr.com/ru/post/1264585/


All Articles