On of the cool features which came back to Ruby 3.0 is flip-flop operator. For those who haven't hear about it this is the quick example:
[1, 2, 3, 4, 5].each do |number| if (number == 2)..(number == 4) print number end end > 2 > 3 > 4
In this example (number == 2)..(number == 4) is the flip-flop operator, which returns false by default. Then turned on by 1st part of it
(number == 2) and turned off by 2nd part
(number == 4). This is why 1 was skipped because the first criteria was not met, then the number was equal to 2 and the whole flip-flop operator started to evaluate to true until it was turned off by reaching number 4.
The cool feature of flip-flop is that 2nd part of it is optional:
[1, 2, 3, 4, 5].each do |number| if (number == 2).. print number end end > 2 > 3 > 4 > 5
Now we never turn off the operator after it reached the 2.
Enough about flip-flops, now let's talk about -n and -e arguments of Ruby.
The first argument -n tells Ruby to execute the code for every input:
while gets #do smth end
and by using
-e Ruby executes the code which is passed to
printf "foo\nbar" | ruby -ne "puts $_"
will print foo and bar on different lines respectively.
$_ is optional so the code above could be simplified to:
printf "foo\nbar" | ruby -ne "puts"
Now having all that in mind let's write some one-liner which prints the CSV file content by skipping the heder:
cat file.csv | ruby -ne 'print $_ if ($. == 2)..'
Here flip-flop is being turned on on 2nd line and never turned off until the end of the file.
But Ruby wouldn't be that great without nifty shortcuts like:
cat file.csv | ruby -ne 'print if 2..'